带和不带斜杠的 nginx 位置
nginx location with and without trailing slash
我想创建一个可以同时捕获 http://example.com and http://example.com/ 的位置和另一个可以捕获其他所有内容的位置。第一个将提供静态 html,另一个用于 api 和其他内容。我试过这个:
location ~ /?$ {
root /var/www/prod/client/www;
}
location ~ /.+ {
#
rewrite ^/(.*) / break;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 1s;
proxy_send_timeout 30s;
proxy_read_timeout 300s;
send_timeout 300s;
proxy_redirect off;
proxy_pass http://backendPro;
}
但是不起作用。我在第一个位置尝试了很多选项,但是当它首先匹配时,第二个不匹配,反之亦然:
location / {
location ~ \/?$ {
location ~ ^/?$ {
其实更简单:
location = / {
# Exact domain match, with or without slash
}
location / {
# Everything except exact domain match
}
因为location = /
更具体,如果只调用域名总是首选(位置块的顺序无关紧要)。
你在 Nginx 中需要的正则表达式比你想象的要少得多,因为正常的位置块匹配每个匹配开头的 URL,所以 location /bla
匹配域中的每个 URL以 /bla 开头(如 /blabla,或 /bla/blu,或 /bla.jpg)。如果您需要捕获组并对其进行处理,我主要推荐正则表达式。
我想创建一个可以同时捕获 http://example.com and http://example.com/ 的位置和另一个可以捕获其他所有内容的位置。第一个将提供静态 html,另一个用于 api 和其他内容。我试过这个:
location ~ /?$ {
root /var/www/prod/client/www;
}
location ~ /.+ {
#
rewrite ^/(.*) / break;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_connect_timeout 1s;
proxy_send_timeout 30s;
proxy_read_timeout 300s;
send_timeout 300s;
proxy_redirect off;
proxy_pass http://backendPro;
}
但是不起作用。我在第一个位置尝试了很多选项,但是当它首先匹配时,第二个不匹配,反之亦然:
location / {
location ~ \/?$ {
location ~ ^/?$ {
其实更简单:
location = / {
# Exact domain match, with or without slash
}
location / {
# Everything except exact domain match
}
因为location = /
更具体,如果只调用域名总是首选(位置块的顺序无关紧要)。
你在 Nginx 中需要的正则表达式比你想象的要少得多,因为正常的位置块匹配每个匹配开头的 URL,所以 location /bla
匹配域中的每个 URL以 /bla 开头(如 /blabla,或 /bla/blu,或 /bla.jpg)。如果您需要捕获组并对其进行处理,我主要推荐正则表达式。