Reputation: 1081
I need to ensure that all permalinks on a given site end with a trailing slash. That is, any URL that refers to a location that doesn't correspond to an actual, individual file. I also need to preserve any query strings and/or anchors that are passed with the URL.
Say I have a page at the following location:
example.com/about/
If I get the following requests, I want them to rewrite as shown:
example.com/about
> example.com/about/
example.com/about?src=fb
> example.com/about/?src=fb
example.com/about#contact
> example.com/about/#contact
example.com/about#contact?src=fb
> example.com/about/#contact?src=fb
However, I want to make sure that I do not rewrite for any actual file paths - anything with a file extension.
This is the regex I have come up with thus far, which only addresses excluding real file paths, and adding a trailing slash when the end of the string doesn't have one:
^([^\.]*$(?<!\/))
I have not yet been able to figure how how to determine whether a trailing slash is present when there are anchors or query strings, and once that's established how to separately capture the parts that should be before the trailing slash and after it in order to assemble the final rewrite.
Upvotes: 3
Views: 2301
Reputation: 1081
As it turns out, the regex I came up with does in fact address all of my rewrite needs. Here is the final result in my Nginx server
configuration:
location / {
try_files $uri $uri/ @rewrites;
}
# Rewrite rules to sanitize and canonicalize URLs
location @rewrites {
rewrite ^([^\.]*$(?<!\/)) $1/ last;
}
Upvotes: 1