Open dum3ng opened 5 years ago
location /api/users {
rewrite ^/api/users(.*)$ /users$1 break;
proxy_pass http://localhost:3000;
}
location /api/about {
rewrite ^/api/about /about last;
proxy_pass http://localhost:3000; // won't work!
}
when using last
, the rewrite is the last directive to execute;
if we put a proxy_pass under this line, it won't work.
Use break
in this situation.
如果一个location由一个以 slash结尾的字符串A定义,而且请求被以下的指令处理:
那么nginx会进行特殊处理。当请求的url与A相同,但是没有以 slash结尾时,nginx会返回 一个永久性301重定向,其location为 A/。
location /user/ {
proxy_pass http://user.example.com;
}
如果发送请求 /user
, 那么结果为
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.14.0 (Ubuntu)
< Date: Thu, 14 May 2020 12:44:54 GMT
< Content-Type: text/html
< Content-Length: 194
< Location: http://example.com/user/
< Connection: keep-alive
如果不想要此行为,那么可以这样:
location /user/ {
proxy_pass http://user.example.com;
}
location = /user {
proxy_pass http://user.example.com;
}
在location 中使用正则
location ~ ^/api/(.*)$ {
proxy_pass http://example.com/$1;
}
在location中必须使用正则中的变量。
location
location modifier
The modifiers:
~
,~*
,^~
,=
,=
modifierExact match
location priority
=
exact match^~
When a request url matches multiple location declaration, first nginx will check the modifier precedence, if two matched location has the same precedence, then the longest location will be used.(?)
redirect
Use
return
: