前言
- nginx version: nginx/1.18.0
- CentOS Linux release 7.6.1810 (Core)
rewrite 语法
rewrite 的官方说明: http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite
Syntax: rewrite regex replacement [flag];
Default: —
Context: server, location, if
If the specified regular expression matches a request URI, URI is changed as specified in the replacement string. The rewrite directives are executed sequentially in order of their appearance in the configuration file. It is possible to terminate further processing of the directives using flags. If a replacement string starts with “http://”, “https://”, or “$scheme”, the processing stops and the redirect is returned to a client.
flag说明:
- last: 本条规则匹配完成后,使用
replacement
重新匹配 location。replacement
部分应为有效的 location。浏览器上的地址不改变。 - break: 本条规则匹配完成后,终止。返回
root
+replacement
指向的内容。replacement
部分应为相对于root
的文件路径。浏览器上的地址不改变。 - redirect: 返回302临时重定向到
replacement
部分给出的地址。replacement
部分应为URL。浏览器上的地址改变。 - permanent: 返回301永久重定向到
replacement
部分给出的地址。replacement
部分应为URL。浏览器上的地址改变。
location /re-last/ {
rewrite /re-last/(.*) /out/$1 last;
}
location /last/ {
rewrite /last/(.*) /re-last/$1 last;
}
location /break {
root /usr/share/nginx/html;
default_type text/html ;
rewrite /break/(.*) /break/$1 break;
}
location /redirect {
rewrite /redirect/(.*) /out/$1 redirect;
}
location /permanent {
rewrite /permanent/(.*) /out/$1 permanent;
}
location ~* /out/(.*) {
default_type text/html ;
return 200 "hello, $1";
}
-
当请求为
“/last/jack”
时,/last/jack
->/re-last/jack
->/out/jack
。访问效果如下图:
-
当请求为
“/break/jack”
时,返回/usr/share/nginx/html/break/jack
文件。访问效果如下图:
-
当请求为
“/redirect/jack”
时,访问效果如下图:
-
当请求为
“/permanent/jack”
时,访问效果如下图:
示例1:在请求路径前追加
location /acticle/ {
rewrite ^/(.*)$ /wode/$1;
}
- 将uri /article/xxx 前面追加 /wode。 /article/xxx 替换成 /wode/article/xxx。
示例2:替换路径
location /article/ {
rewrite ^/article/(.*)$ /wenzhang/$1;
}
- 将uri /article/xxx 替换成 /wenzhang/xxx。