1

I need to enforce trailing slashes on a particular set of URIs on my site.

The URIs take the following format: /foo/bar1/bar2/bar3/?abc, where /foo/ is common across all dynamic and also a valid URI on it's own.

All and only dynamic URIs will match the regex ^(.*[^/])$ assuming a prefix check on /foo/ was performed.

My code currently looks like this:

location /foo/ {
  location ~* ^(.*[^/])$ {
    return 302 $baseUrl/$1/$is_args$args;
  }
}

This, however, causes 404s on all /foo/.*, though it does successfully insert the slash as intended.

Clearly, if it matches the outer location, but not the inner one, it fails.

What I'm looking for then, is a statement that causes the execution to step back out of outer location.

Note:

I realize I could just say

location ~* ^(/foo/.*[^/])$ {
  return 302 $baseUrl/$1/$is_args$args;
}

but I'd like to avoid it because of the performance hit of regex. Don't want to deal with that on non-candidate pages.

  • How are the URIs with a trailing / processed. Couldn't you just include that within the location block. You either need to duplicate the code or use a regular expression. – Richard Smith Jun 13 at 7:21
  • @RichardSmith, it looks like duplicating code was the right choice. – B. Huntemann Jun 14 at 15:03
0

After some more research and experimentation, I ended up moving this condition into the final

location / {
   try files  . . .
}

to get something like

location / {
  ## Enforce trailing slash on dynamic pages
  location /foo/ {
    location ~* ^(.*[^/])$ {
      return 302 $baseUrl/$1/$is_args$args;
    }
    try_files $uri $uri/ /index.php?$args;
  }

  try_files $uri $uri/ /index.php?$args;
}

Still a bit messy and having duplicate code, but it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.