zeachco
zeachco

Reputation: 780

Configure nginx to rewrite hashes on all paths

I use nginx as a static file server first and try to rewrite all uri if they contain hashes to point to a mock directory.

It might be more clear with an example

let's say the user request pages url like theses :

/api/some/path/to/ecbac7cb-21ca-3d22-98ed-4d063f138d0b/some/other/path/02167621-5c01-45c5-98ba-eb3ba1bf4b2a/list

/api/some/other/path/to/ecbac7cb-21ca-3d22-98ed-4d063f138d0b

I want to try to get the file at first but the fallback would be somthing like this

/api/some/path/to/__any_hash__/some/other/path/__any_hash__/list.json

/api/some/other/path/to/__any_hash__.json

here is a config I tried to far... but obviously, it's not working.

server {
 ...
 location /api {
  try_files $uri $uri/index.html $uri.html $uri.json $uri.xml @rewrites;
 }

 location @rewrites {
  rewrite /([0-9\-a-f]{36})/ __any_hash__ break;
  try_files $uri.xml $uri.json @backend;
 }

Anyone have an idea?

Upvotes: 2

Views: 1250

Answers (1)

Richard Smith
Richard Smith

Reputation: 49762

Your location @rewrites should probably look like this:

location @rewrites {
    rewrite "^(.*)/[0-9\-a-f]{36}(/.*)$" $1/__any_hash__$2 last;
    return 404;
}

The $1 and $2 capture the URI fragment before and after the hash to be substituted. The last causes the location /api to be reattempted after the substitution. The process will loop until all of the substitutions are made. The return 404 is only invoked if the fully substituted URI fails to find a file.

Upvotes: 2

Related Questions