3

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.

2
  • 1
    So two of the urls can be handle by nginx but not without sending a 301 or 302. But example.com/about#contact > example.com/about/#contact and other one with # can only be done using javascript but anything after # is never sent to the webserver Commented Sep 26, 2017 at 9:11
  • Good point, I didn't even think about that. That actually should simplify the regex I need to have. Commented Sep 26, 2017 at 9:36

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.