1、重写(permanent)
说明:返回永久重定向状态码301
场景:https://test.com/t/index.html 转发到 https://www.baidu.com/
location = /t/index.html {
rewrite /t/index.html https://www.baidu.com/ permanent;
}
2、 重写(break)
说明:将url重写成新的地址,不是转发请求到新的location上去执行。
场景1:将 https://test.com/ 转发到 https://test.com/admin
执行原理:直接将 / 替换成 /admin ,组成 https://test.com/admin 转发到服务器上。
location / {
rewrite / /admin/ break;
expries off;
}
场景2:将 https://test.com/t/admin 转发到 https://test.com/web/t/admin
执行原理:$1 表示 /t/ 后面 (.*) 匹配到的任意字符 admin,将 https://test.com/t/$1 重写成 https://test.com/web/t/$1
location ~ ^/t/(.*)$ {
rewrite ^/t/(.*)$ /web/t/$1 break;
expries off;
}
3、匹配扩展名
场景:匹配以 /t 开头和 html 结尾的请求,例如: https://test.com/t/index.html?a=1
location ~ ^/t/(.*)\.html(.*)$ {
expries off;
}
4、静态资源配置
场景:nginx存放静态资源,使用 root 指定静态资源路径,例如:当访问 https://test.com/res/report.html?type=about 时,到 /opt/app/nginx/static/res 目录中找到静态资源 about.html
location = /res/report.html {
if ($arg_type != ""){
rewrite /res/report.html /res/$arg_type.html break;
}
root /opt/app/nginx/static/;
}