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;
}
...
}
CodePudding user response:
You can use rewrite directive either at the server or at the location contexts. The difference is the request processing phase where that rewrite 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 a rewrite directive at the location context, you should use last flag for the rewrite directive instead of break 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 either
location /not-supported/ {
internal;
}
location / {
if ($outdated = 1) {
rewrite ^ /not-supported/index.html last;
}
try_files $uri $uri/ /index.html;
}
or
if ($outdated = 1) {
rewrite ^ /not-supported/index.html;
}
location /not-supported/ {
internal;
}
location / {
try_files $uri $uri/ /index.html;
}
You can have that non-supported directory with the index.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 the location /not-supported/ { ... }). Make sure that rewrite rule do not interfere with any others may be present at the server context.
CodePudding user response:
Made it work by:
http {
# https://user-agents.net/browsers
map $http_user_agent $outdated {
default 0;
"~Opera" 1; # Opera all
"~MSIE" 1; # MSIE all
"~Trident/[1-7]\." 1; # MSIE all
"~Chrome/(([1-9]{1})|([0-7]{1}[0-9]{1})|(8[0-6]{1}))\." 1; # Chrome 1.* - 86.*
"~YaBrowser/(([1-9]{1})|([1-9]{1}[0-8]{1}))\." 1; # Yandex 1.* - 18.*
"~Firefox/(([1-9]{1})|([0-7]{1}[0-9]{1})|(8[0-3]{1}))\." 1; # Firefox 1.* - 83.*
"~EdgA?/(([1-9]{1})|([0-7]{1}[0-9]{1})|(8[0-6]{1}))\." 1; # Edge/MobileEdge 1.* - 86.*
"~Version/(([1-9]{1})|([1-9]{1}[0-1]{1}))\." 1; # Safari 1.* - 11.*
}
server {
listen 8080 default_server;
root /opt/app-root/src;
if ($uri ~ /not-supported) {
set $outdated 0;
}
if ($outdated = 1) {
rewrite ^ /not-supported/index.html last;
}
location / {
.......
