Redirects

Issuing a HTTP redirect is easy. Both internal and external locations are supported. By locations we mean, paths, subdomains, domains and e.t.c.

From Handler

  1. app.Get("/", func(ctx iris.Context) {
  2. ctx.Redirect("https://golang.org/dl", iris.StatusMovedPermanently)
  3. })

Issuing a HTTP redirect from POST.

  1. app.Post("/", func(ctx iris.Context) {
  2. ctx.Redirect("/login", iris.StatusFound)
  3. })

Issuing a local router redirect from a Handler, use Application.ServeHTTPC or Exec() like below.

  1. app.Get("/test", func(ctx iris.Context) {
  2. r := ctx.Request()
  3. r.URL.Path = "/test2"
  4. ctx.Application().ServeHTTPC(ctx)
  5. // OR
  6. // ctx.Exec("GET", "/test2")
  7. })
  8. app.Get("/test2", func(ctx iris.Context) {
  9. ctx.JSON(iris.Map{"hello": "world"})
  10. })

Globally

Use the syntax we all love.

  1. import "github.com/kataras/iris/v12/middleware/rewrite"
  1. func main() {
  2. app := iris.New()
  3. // [...routes]
  4. redirects := rewrite.Load("redirects.yml")
  5. app.WrapRouter(redirects)
  6. app.Listen(":80")
  7. }

The "redirects.yml" file looks like that:

  1. RedirectMatch:
  2. # Redirects /seo/* to /*
  3. - 301 /seo/(.*) /$1
  4. # Redirects /docs/v12* to /docs
  5. - 301 /docs/v12(.*) /docs
  6. # Redirects /old(.*) to /
  7. - 301 /old(.*) /
  8. # Redirects http or https://test.* to http or https://newtest.*
  9. - 301 ^(http|https)://test.(.*) $1://newtest.$2
  10. # Handles /*.json or .xml as *?format=json or xml,
  11. # without redirect. See /users route.
  12. # When Code is 0 then it does not redirect the request,
  13. # instead it changes the request URL
  14. # and leaves a route handle the request.
  15. - 0 /(.*).(json|xml) /$1?format=$2
  16. # Redirects root domain to www.
  17. # Creation of a www subdomain inside the Application is unnecessary,
  18. # all requests are handled by the root Application itself.
  19. PrimarySubdomain: www

The full code can be found at the rewrite middleware example.