Efficient remove trailing slash redirect

I’ve been changing a few of my Caddy config files recently to include redirects to remove trailing slashes from any URL.

I searched Google, this forum and the documentation but nothing seemed to specifically mention a solution to this problem, so I cam up with the following:

rewrite {
    r ^/(.*)/$
    to /{1}
}

redir 301 {
    if {path} not /
    if {path} ends_with /
    / {rewrite_uri}
}

This works perfectly fine, but it would be nice to avoid the need for the regular expression and rewrite steps.

Is there a more efficient way that I can achieve the same result without having to resort to regular expressions and rewrites?

In my experience this is quite a common requirement, so if not is it something that could be considered for a future version of Caddy in some form?

There’s no more efficient method I know of.

One suggestion, though - currently you’re regex checking every request. You can reduce the load slightly by copying the if {path} ends_with / check over to the rewrite, which will substring check every request and skip the regex capture if it doesn’t need it. Could save you a lot of cycles if you’ve got a high request count.

We generally welcome any feature requests over at the Github repository. There’s already some code for trailing slash handling, which the static file server uses to ensure canonical requests for files and directories. I’m sure similar code could be used to extend either existing redir or rewrite functionality, or perhaps a small directive to set a trailing slash policy for the whole site, but it would need to not conflict with the existing code.

Feel free to post a new issue as a feature request for discussion there:

https://github.com/mholt/caddy/issues

1 Like

Thanks for the quick reply :slight_smile:

I didn’t realise that the if lines would be checked before the regular expression so I’ll definitely copy that over to the rewrite now.

Thank you for the link to the source code in Caddy too. I’ll try to find some time to look over the code, hopefully this week sometime to see if it’s something I could implement. If I don’t get any time I’ll still make sure I post an issue so it’s on record somewhere other than this forum.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.