Nginx:地址重写(return和rewrite)

Nginx的重写指令用于改变客户端的URL请求。主要有returnrewrite。两个指令都有重写URL的能力,但rewrite支持更复杂的功能。

Return指令

server中返回 301 重定向:

server {
        listen 80;
        server_name www.olddomain.com;
        return 301 $scheme://www.newdomain.com$request_uri;
}

location中返回 301 重定向:

location = /tutorial/learning-nginx {
     return 301 $scheme://example.com/nginx/understanding-nginx
}

Rewrite指令

语法介绍

rewrite regex replacement-url [flag];
  • regex: 正则表达式
  • replacement-url: 替换的URL
  • flag: 用于进行一些额外的处理

不同flag的效果:

flag 说明
last 停止解析,并开始搜索与更改后的URI相匹配的location;
break 中止 rewrite,不再继续匹配
redirect 返回临时重定向的 HTTP 状态 302
permanent 返回永久重定向的 HTTP 状态 301

注意:rewrite只能返回301和302状态码,如果需要返回其他状态码,可以在rewrite命令后使用return

案例

简单案例

https://example.com/nginx-tutorial重写为https://example.com/somePage.html

location = /nginx-tutorial 
{ 
    rewrite ^/nginx-tutorial?$ /somePage.html last; 
}
动态替换案例

https://www.example.com/user.php?id=11重写为https://exampleshop.com/user/11

location = /user.php 
{ 
    rewrite ^/user.php?id=([0-9]+)$ /user/$1 last; 
}

其中$1表示regex中第一个括号中的值,第二个括号中的值可通过$2获取

手机访问重定向网址

https://www.example.com重写为https://m.exampleshop.com

location = /
{
    if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
    rewrite ^(.*) https://m.example.com$1 redirect;
    }
}
原文地址:https://www.cnblogs.com/testopsfeng/p/15294660.html