0
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-23 22:27:38 -05:00
caddy/middleware/redirect/redirect.go

78 lines
1.8 KiB
Go
Raw Normal View History

// Package redirect is middleware for redirecting certain requests
2015-01-13 14:43:45 -05:00
// to other locations.
package redirect
import (
"net/http"
2015-03-29 22:48:53 -05:00
"strings"
"github.com/mholt/caddy/middleware"
)
// New creates a new redirect middleware.
func New(c middleware.Controller) (middleware.Middleware, error) {
2015-03-29 22:48:53 -05:00
var redirects []Redirect
for c.Next() {
2015-03-29 22:48:53 -05:00
var rule Redirect
args := c.RemainingArgs()
2015-03-29 22:48:53 -05:00
if len(args) == 1 {
// Only 'To' specified
rule.From = "/"
rule.To = c.Val()
rule.Code = 307 // TODO: Consider 301 instead?
redirects = append(redirects, rule)
} else if len(args) == 3 {
// From, To, and Code specified
rule.From = args[0]
rule.To = args[1]
if code, ok := httpRedirs[args[2]]; !ok {
return nil, c.Err("Invalid redirect code '" + c.Val() + "'")
} else {
rule.Code = code
}
redirects = append(redirects, rule)
} else {
2015-03-29 22:48:53 -05:00
return nil, c.ArgErr()
}
}
return func(next middleware.Handler) middleware.Handler {
return middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
for _, rule := range redirects {
2015-03-29 22:48:53 -05:00
if middleware.Path(r.URL.Path).Matches(rule.From) {
if rule.From == "/" {
// Catchall redirect preserves path (TODO: This should be made more consistent...)
http.Redirect(w, r, strings.TrimSuffix(rule.To, "/")+r.URL.Path, rule.Code)
return 0, nil
}
2015-01-13 14:43:45 -05:00
http.Redirect(w, r, rule.To, rule.Code)
return 0, nil
2015-01-13 14:43:45 -05:00
}
}
return next.ServeHTTP(w, r)
})
}, nil
}
// redirect describes an HTTP redirect rule.
2015-03-29 22:48:53 -05:00
type Redirect struct {
From string
To string
Code int
2015-01-13 14:43:45 -05:00
}
// httpRedirs is a list of supported HTTP redirect codes.
var httpRedirs = map[string]int{
"300": 300,
"301": 301,
"302": 302,
"303": 303,
"304": 304,
"305": 305,
"306": 306,
"307": 307,
"308": 308,
}