Example nginx.conf, I’d like to move conditional rewrite from location directives, but have no idea how:
# https://user-agents.net/browsers
map $http_user_agent $outdated {
default 0;
...
}
server {
...
location ~ (not-supported) {
# empty
}
location / {
if ($outdated = 1) {
rewrite ^ /not-supported/index.html break;
}
try_files $uri $uri/ /index.html =404;
}
...
}
2
Answers
Made it work by:
You can use
rewrite
directive either at theserver
or at thelocation
contexts. The difference is the request processing phase where thatrewrite
directive will be processed (NGX_HTTP_SERVER_REWRITE_PHASE
for the firest case,NGX_HTTP_REWRITE_PHASE
for the second one). Avoid regular expressions whenever possible. When you use arewrite
directive at thelocation
context, you should uselast
flag for therewrite
directive instead ofbreak
one to force new search of the location for the rewritten URI. I also recommend to make it internal to prevent direct access to the/not-supported/
directory. So use eitheror
You can have that
non-supported
directory with theindex.html
file inside either under your web root directory or anywhere else (for the last case you’ll need to define a custom root for thelocation /not-supported/ { ... }
). Make sure that rewrite rule do not interfere with any others may be present at theserver
context.