Rewrite rule to try with and without trailing slash


(Jose Jimenez) #1

Hello,

I am using caddy in a small production server. So far everything runs fine, however, I’d like to add a rewrite rule to try the URL with and without trailing slash.

I am not sure if the overall construction is correct, especially the rewrite rule,
rewrite {
regexp ^(.+)/$
to {1} {1}/ /404/
}

Should I use ^(.+)/$ or ^(.+)/?$ (added question mark for making optional the trailing slash in the regex)?

For completeness, I have attached below the main part of the configuration.

Thank you,
Jose

 \# Locale detection
 locale en es {
   detect cookie header
 }
 \# Home redirection
 redir {
   if {path} is /
   / /{>Detected-Locale}/ 302
 }
 \# Try in order: no_slash, with_slash, 404
 rewrite {
   regexp ^(.+)/$
   to {1} {1}/ /404/
 }
 \# Permanent redirection no_slash to with_slash
 redir 301 {
   if {uri} not_ends_with /
   if {rewrite_uri} ends_with /
   / {rewrite_uri}
 }
 \# 404 Not Found
 redir {
   if {rewrite_uri} is /404/
   / /{>Detected-Locale}/404.html 301
 }
 \# https://www.fastly.com/blog/best-practices-using-vary-header
 header / Vary "Cookie, Accept-Language, Vary: Accept-Encoding"
 
 \# Expires: 7 days
 expires {
   match (.css|.js|.jpg|.png)$ 7d
 }


(Toby Allen) #2

What sort of results are you getting when you test this caddyfile?