语法:rewrite regex replacement [flag];;
默认值:——
可配置段:server, location
作用:通过正则表达式的使用来改变URI。可以同时存在一个或多个指令。需要按照顺序依次对URL进行匹配和处理。
示例:
rewrite ^/(.*) http://www.baidu.com/$1 permanent;
解释:
rewrite:固定关键字,表示开始进行rewrite匹配规则。
正则表达式^/(.*):正则表达式,匹配完整的域名和后面的路径地址。
replacement为http://www.baidu.com/$1:其中$1是取regex部分()里面的内容。如果匹配成功后跳转到的URL。
flag为permanent:代表永久重定向,即跳转到 http://www.baidu.com/$1 地址上
3 redirect #返回302临时重定向,浏览器地址会显示跳转新的URL地址。
4 permanent #返回301永久重定向,浏览器地址会显示跳转新的URL地址。
示例1 :请求转发不要斜杠处理 ---break
请求: https://ip/abc/cc/xx
location /abc/ {
proxy_pass http://localhost:8084/;
}
实际请求的 http://localhost:8084/cc/xx
如何让配置proxy_pass http://localhost:8084/; 改为 proxy_pass http://localhost:8084 ;
location /abc/ {
rewrite ^/abc/(.*)$ /$1 break;
proxy_pass http://localhost:8084;
}
效果也是: http://localhost:8084/cc/xx
示例2: 请求重定向到新地址 ---redirect
[root@nginx01 ~]# vi /etc/nginx/conf.d/rewrite02.conf
server {
listen 80;
server_name file.linuxds.com;
access_log /var/log/nginx/file.access.log main;
error_log /var/log/nginx/file.error.log warn;
location ~ .* {
root /usr/share/nginx/file;
if ( !-e $request_filename ) {
rewrite ^ http://www.cnblogs.com redirect;
}
}
}
配置解释:
结合if指令来对nginx请求进行判断,若访问http://file.linuxds.com的资源存在root目录,则返回,若当前请求的资源文件不存在,则进行重定向跳转,重定向至 http://www.cnblogs.com。
页面直接302定向到 http://www.cnblogs.com 中
[root@nginx01 ~]# vi /etc/nginx/conf.d/rewrite06.conf
server {
listen 80;
server_name rewrite.linuxds.com;
access_log /var/log/nginx/rewrite.access.log main;
error_log /var/log/nginx/rewrite.error.log warn;
location ~ .* {
root /usr/share/nginx/rewrite;
rewrite /rewrite.html /index.html redirect;
}
}
配置解释:访问 /redirect.html 的时候,页面直接302定向到 /index.html中。
示例3: 配置解释:访问 /last.html 的时候,页面内容重写到 /index.html 中 ---last
[root@nginx01 ~]# vi /etc/nginx/conf.d/rewrite04.conf
server {
listen 80;
server_name last.linuxds.com;
access_log /var/log/nginx/last.access.log main;
error_log /var/log/nginx/last.error.log warn;
location ~ .* {
root /usr/share/nginx/last;
rewrite /last.html /index.html last;
}
}
示例4 重定向 301 permanent
[root@nginx01 ~]# vi /etc/nginx/conf.d/rewrite07.conf
server {
listen 80;
server_name permanent.linuxds.com;
access_log /var/log/nginx/permanent.access.log main;
error_log /var/log/nginx/permanent.error.log warn;
location ~ .* {
root /usr/share/nginx/permanent;
rewrite /permanent.html /index.html permanent;
}
}
配置解释:访问 /permanent.html 的时候,页面直接301定向到 /index.html中。
更多推荐