nginx-rewrite

nginx rewrite #

rewrite regex replacement [flag];

Example:
rewrite ^/(.*)$ /static/$1 last;
rewrite ^/account$ https://xxx.com/user permanent;

flag:

  • last: 本条规则匹配完成后继续向下匹配新的location URI规则,使用alias指定源必须用last不能用break并且要注意死循环。
  • break: 本条规则匹配完成后终止,不在匹配任何规则。
  • redirect: 302重定向
  • permanent: 301重定向

注意事项:重写规则与重定向地址 #

  1. 允许手动指定查询参数。
  2. 重定向地址会自动拼接原始查询参数,不论是否手动指定了查询参数。

如果重写规则是一个完整链接,则重定向地址也是一个完整链接。 如果重写规则是一个相对路径,则重定向地址也是一个相对路径。 如果重写规则是一个绝对路径,则重定向地址是当前协议+域名+端口号+绝对路径。

如果当前代理是二级代理,则重定向时建议配置完整链接,或者添加动态域名 $http_x_forwarded_proto://$host:$http_x_forwarded_port(80或443端口可以去掉端口号部分)。

用例1:添加前缀路径 #

以下四种情况效果一致:

text
rewrite ^ /context$uri redirect;
rewrite ^.*$ /context$uri redirect;
rewrite ^(.*)$ /context$1 redirect;

# 因为return不会自动拼接查询参数,所以这里使用携带查询参数的request_uri而不是uri。
return 302 /context$request_uri;

输入:https://example.com/demo/123
输出:https://example.com/context/demo/123

用例2:替换前缀路径 #

text
rewrite ^/old/(.*)$ /new/$1 redirect;

输入:https://example.com/old/demo/123
输出:https://example.com/new/demo/123

用例3:路径参数改为查询参数 #

text
# 原始查询参数会自动拼接到id参数后面。
rewrite ^/get/(.*)$ /get?id=$1 redirect;

输入:https://example.com/get/123
输出:https://example.com/get?id=123

用例4:查询参数改为路径参数 #

text
# 1.arg_xxx缺省值为空串;
# 2.重定向后查询参数id会被保留下来。
rewrite ^/get$ /get/$arg_id redirect;

输入:https://example.com/get?id=123
输出:https://example.com/get/123?id=123
2024年10月13日