简体   繁体   中英

Nginx rewrite: add trailing slash, preserve anchors and query strings

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.

Example

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.

What I have so far

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM