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

Made catch-all redirects possible

This commit is contained in:
Matthew Holt 2015-03-29 21:48:53 -06:00
parent 4e9c432c14
commit 0a9a19305c

View file

@ -4,47 +4,49 @@ package redirect
import ( import (
"net/http" "net/http"
"strings"
"github.com/mholt/caddy/middleware" "github.com/mholt/caddy/middleware"
) )
// New creates a new redirect middleware. // New creates a new redirect middleware.
func New(c middleware.Controller) (middleware.Middleware, error) { func New(c middleware.Controller) (middleware.Middleware, error) {
var redirects []redirect var redirects []Redirect
for c.Next() { for c.Next() {
var rule redirect var rule Redirect
args := c.RemainingArgs()
// From if len(args) == 1 {
if !c.NextArg() { // Only 'To' specified
return nil, c.ArgErr() rule.From = "/"
}
rule.From = c.Val()
// To
if !c.NextArg() {
return nil, c.ArgErr()
}
rule.To = c.Val() rule.To = c.Val()
rule.Code = 307 // TODO: Consider 301 instead?
// Status Code redirects = append(redirects, rule)
if !c.NextArg() { } else if len(args) == 3 {
return nil, c.ArgErr() // From, To, and Code specified
} rule.From = args[0]
rule.To = args[1]
if code, ok := httpRedirs[c.Val()]; !ok { if code, ok := httpRedirs[args[2]]; !ok {
return nil, c.Err("Invalid redirect code '" + c.Val() + "'") return nil, c.Err("Invalid redirect code '" + c.Val() + "'")
} else { } else {
rule.Code = code rule.Code = code
} }
redirects = append(redirects, rule) redirects = append(redirects, rule)
} else {
return nil, c.ArgErr()
}
} }
return func(next middleware.HandlerFunc) middleware.HandlerFunc { return func(next middleware.HandlerFunc) middleware.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) (int, error) { return func(w http.ResponseWriter, r *http.Request) (int, error) {
for _, rule := range redirects { for _, rule := range redirects {
if r.URL.Path == rule.From { 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
}
http.Redirect(w, r, rule.To, rule.Code) http.Redirect(w, r, rule.To, rule.Code)
return 0, nil return 0, nil
} }
@ -55,7 +57,7 @@ func New(c middleware.Controller) (middleware.Middleware, error) {
} }
// redirect describes an HTTP redirect rule. // redirect describes an HTTP redirect rule.
type redirect struct { type Redirect struct {
From string From string
To string To string
Code int Code int