fiber/docs/middleware/redirect.md
Isaac Andrade 4321dfed55
♻️ refactor: Change c.Redirect() default status (#3415)
* Set default redirect response status to 303 SeeOther

Closes #3405

In some browsers, redirect status 302 Found sometimes is used to change
the HTTP verb of the response from what the user set to what was used in
the request. Changing to 303 SeeOther in the default works more like
expected: it defaults to GET and can be overriden by the user.

* Add tests to Redirect default status change.

* Update docs.

* Fix remaining tests to reflect redirect 303 status as the new default. Reflect that in docs/whats_new.md

* Update redirect_test.go

* Fix code review hints

---------

Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com>
Co-authored-by: René <rene@gofiber.io>
2025-05-12 14:56:23 +02:00

1.9 KiB

id
id
redirect

Redirect

Redirection middleware for Fiber.

Signatures

func New(config ...Config) fiber.Handler

Examples

package main

import (
    "github.com/gofiber/fiber/v3"
    "github.com/gofiber/fiber/v3/middleware/redirect"
)

func main() {
    app := fiber.New()
    
    app.Use(redirect.New(redirect.Config{
      Rules: map[string]string{
        "/old":   "/new",
        "/old/*": "/new/$1",
      },
      StatusCode: fiber.StatusMovedPermanently,
    }))
    
    app.Get("/new", func(c fiber.Ctx) error {
      return c.SendString("Hello, World!")
    })
    app.Get("/new/*", func(c fiber.Ctx) error {
      return c.SendString("Wildcard: " + c.Params("*"))
    })
    
    app.Listen(":3000")
}

Test

curl http://localhost:3000/old
curl http://localhost:3000/old/hello

Config

Property Type Description Default
Next func(fiber.Ctx) bool Filter defines a function to skip middleware. nil
Rules map[string]string Rules defines the URL path rewrite rules. The values captured in asterisk can be retrieved by index e.g. $1, $2 and so on. Required
StatusCode int The status code when redirecting. This is ignored if Redirect is disabled. 302 Temporary Redirect

Default Config

var ConfigDefault = Config{
    StatusCode: fiber.StatusFound,
}