Suppose you have a request for the following json file.
e.g. https://example.com/aaa/bbb/ccc.json
I want to have Nginx handle 'aaa' as a fixed string, and 'bbb' and 'ccc' as changing strings.
In this case, I want the proxy to work ignoring the 'bbb' path in the URL. How should I describe this in a lcoation block in Nginx?
location /aaa {
# I want to ignore 'bbb' path and return ccc.json. 'ccc' varies.
alias /mydirectory/aaa;
try_files $url;
}
CodePudding user response:
Locations in nginx can be defined with regular expressions (docs).
Depending on how specific you'd like to be, you might choose ~
for case-sensitive URI matching or ~*
for case-insensitive URI matching. ^~
is also available as a prefix match, but note a match here will stop the engine from performing additional regex matching. Caveat emptor.
Something like this would be a relatively straightforward way to "absorb" the bbb
(or any other combo of 1 or more letters, upper and lower case):
location ~ ^\/aaa\/[a-zA-Z] {
...
}
In order to capture the ccc.json
, you'll want to add a capturing group as well:
location ~ ^\/aaa\/[a-zA-Z] \/([\w\.] ) {
return 200 '$1';
}
Bonus: if you're using PCRE 7 (docs), you can name your capture:
location ~ ^\/aaa\/[a-zA-Z] \/(?<filename>[\w\.] ) {
return 200 '$filename';
}