nginx 根据路由匹配和请求参数配置 301 重定向

nginx 重定向常用两个配置 rewritereturn

rewrite 命令

使用方法:

1
rewrite 正则表达式 替换目标 flag标记

flag标记可以用以下几种格式:

1
2
3
4
last – 停止处理后续rewrite指令集,跳出location作用域,并开始搜索与更改后的URI相匹配的location,URL地址不变
break – 停止处理后续rewrite指令集,不会跳出location作用域,不再进行重新查找,终止匹配,URL地址不变
redirect – 返回302临时重定向,浏览器地址栏会显示跳转后的URL地址,爬虫不会更新URL
permanent – 返回301永久重定向,浏览器地址栏会显示跳转后的URL地址,爬虫会更新URL

示例:

1
2
3
if ($http_host = www.test.com) {
rewrite (.*) http://test.com$1;
}

return 命令

return是rewrite模块里的执行,执行阶段是rewrtie,可以写在 server、location、if 里面。

使用方法:

1
2
3
return code [text];
return code URL;
return URL; # 不带返回码,默认返回302临时重定向

示例:

1
2
3
if ($http_host = www.test.com) {
return 301 http://test.com$args;
}

实际应用场景

需求1:

需要将原有 v1 路径重定向到 v2 去,比如 http://localhost:9999/v1/details/11223344 重定向到 http://localhost:9999/v2/details/11223344

nginx 配置

1
2
3
4
5
6
7
8
9
server {
listen 9999;
server_name localhost;

# 重定向配置
location ~* /v1/details/(.+) {
return 301 /v2/details/$1;
}
}

需求2:

由于历史原因,还有如下路径 http://localhost:9999/page/l/?s=11&c=22&id=11223344 也需要重定向到 http://localhost:9999/v2/details/11223344

从路径来看,以上 /page/l/ 是公用路径,通过参数不同来实现页面,跟很多的 MVC 框架控制路由思路大致一样。

所以这儿不能使用路由来匹配了,需要通过请求参数来重定向,配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server {
listen 9999;
server_name localhost;

# 重定向配置
location ~* /v1/details/(.+) {
return 301 /v2/details/$1;
}
location ^~ /page/l/ {
set $flag 0;
if ($arg_c = 22) { # 表示请求参数 c === 22 时候,设置 flag 为 *1
set $flag "${flag}1";
}
if ($arg_s = 11) { # 表示请求参数 s === 11 时候,设置 flag 为 *2
set $flag "${flag}2";
}
if ($flag = "012") {
return 301 /v2/details/$arg_id; # 如果以上两个 if 全部命中,则地址重定向
}
}
}

添加以上配置,重启 nginx 之后,即可开启对应地址的 301 重定向。

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2022-02-02/nginx-301/

如果您觉得文章不错,可以点击文章中的广告支持一下!