Nginx 重定向

本文最后更新于:2024年3月18日 凌晨

Nginx 重定向

301永久重定向

  • 浏览器地址会显示跳转新的URL地址。
1
2
3
4
5
server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}

302临时重定向

  • 浏览器地址会显示跳转新的URL地址。
1
2
3
4
5
6
7
8
server {
listen 80;
server_name yourdomain.com; #需要将yourdomain.com替换成证书绑定的域名。
rewrite ^(.*)$ https://$host$1; #将所有HTTP请求通过rewrite指令重定向到HTTPS
location / {
index index.html index.htm;
}
}

根据客户端重定向

  • 如果请求来自于移动端,则重定向至移动站点。
1
2
3
4
5
6
7
8
9
10
server {
listen 80;
server_name example.com;
index index.html index.php;
root html;
if ( $http_user_agent ~* "(Android)|(iPhone)|(Mobile)|(WAP)|(UCWEB)" ){
rewrite ^/$ http://www.m.example.com permanent;
}
}

  • permanent表示301永久重定向。

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!