问题:
需要给我的网站设置nginx的301跳转,但正则表达式学得不好,不知道怎么写,请求帮助。
旧网站域名为www.A.com,新网站域名为www.B.com。具体细节如下:
1、所有/daohang子目录的url,分以下两种情况:
(1)网址id为1至400、495至638的,直接跳转,例如:
www.A.com/daohang/1.html 跳转到 www.B.com/daohang/1.html
www.A.com/daohang/100.html 跳转到 www.B.com/daohang/100.html
www.A.com/daohang/400.html 跳转到 www.B.com/daohang/400.html
www.A.com/daohang/495.html 跳转到 www.B.com/daohang/495.html
www.A.com/daohang/638.html 跳转到 www.B.com/daohang/638.html
(2)网址id为401至494的,跳转到新的子目录weixin,且文件名增加前缀“html_”,例如:
www.A.com/daohang/401.html 跳转到 www.B.com/weixin/html_401.html
www.A.com/daohang/494.html 跳转到 www.B.com/weixin/html_494.html
2、根目录、所有其他子目录的网页,均直接跳转,例如:
www.A.com 跳转到 www.B.com
www.A.com/view/1.html 跳转到 www.B.com/view/1.html
www.A.com/dans/1.html 跳转到 www.B.com/dans/1.html
参考gpt:
要实现上述需求,你可以在 Nginx 的配置文件中使用 rewrite 指令来进行重定向。下面是一个基于你的需求的示例配置:
server {
listen 80;
server_name www.A.com;
location /daohang {
rewrite ^/daohang/(1|100|400|495|638)\.html$ http://www.B.com$uri redirect;
rewrite ^/daohang/(401|494)\.html$ http://www.B.com/weixin/html_$1.html redirect;
rewrite ^/daohang/(.*)$ http://www.B.com/daohang/$1 redirect;
}
location / {
rewrite ^(.*)$ http://www.B.com$1 redirect;
}
}
上述配置中,通过在 location 块中使用 rewrite 指令来实现不同的重定向规则。其中,正则表达式使用 ^ 表示开头,$ 表示结尾,. 表示匹配实际的点号而不是正则表达式中的任意字符。
请确保在你的 Nginx 配置文件中修改相应的虚拟主机配置,并重启 Nginx 服务器使配置生效。
使用两个server块来分别处理主域名和子目录的跳转。对于主域名的跳转,我们将所有请求都重定向到新的域名上。对于子目录的跳转,我们使用location指令来匹配/daohang路径,然后使用rewrite指令和正则表达式对不同的URL进行跳转。
server {
listen 80;
server_name www.A.com; # 旧域名
return 301 $scheme://www.B.com$request_uri;
}
server {
listen 80;
server_name www.A.com;
location /daohang {
rewrite ^/daohang/([1-4]\d{0,2}|[56]3[89])\.html$ http://www.B.com/daohang/$1.html permanent;
rewrite ^/daohang/([45]\d{0,2})\.html$ http://www.B.com/weixin/html_$1.html permanent;
}
}
试试
server {
listen 80;
server_name www.A.com;
rewrite ^/(daohang/([1-9]|[1-3][0-9]|400|495-638).html)$ https://www.B.com/$1 permanent;
rewrite ^/(daohang/([4][0-1][0-9]|[4-4][0-9][0-9]).html)$ https://www.B.com/weixin/html_$2.html permanent;
rewrite ^ https://www.B.com$request_uri? permanent;
}