Nginx 配置 HTTP 跳转 HTTPS

状态码
| 状态码 | 英文描述 | 中文释义 | |
|---|
| 301 | Moved Permanently | 永久移动。请求的资源已被永久的移动到新URI,返回信息会包括新的URI,浏览器会自动定向到新URI。今后任何新的请求都应使用新的URI代替 | |
| 302 | Found | 临时移动。与301类似。但资源只是临时被移动。客户端应继续使用原有URI | |
| 303 | See Other | 查看其它地址。与301类似。使用GET和POST请求查看 | |
| 307 | Temporary Redirect | 临时重定向。与302类似。使用GET请求重定向 | |
配置方法
- 根域名跳转到https
server
{
listen 80;
#listen [::]:80;
server_name xp.sb ; # 指定固定域名,如果不指定固定域名可以把这一行去掉或者注释。
index index.html index.htm index.php default.html default.htm default.php;
root /home/wwwroot/webroot;
return 301 https://$host$request_uri;
- 正则跳转,不管带不带www的都跳转到不带www的根域名的https,不需要指定固定的域名。
server
{
listen 80;
#listen [::]:80;
server_name ~^(?:www\.)?(.+)$;
index index.html index.htm index.php default.html default.htm default.php;
root /home/wwwroot/webroot;
return 301 https://$1$request_uri;
- 根据端口和域名判断跳转
#方法2,判断443端口
if ($server_port !~ 443){ return 301 https://example.com$request_uri;}
#方法3,判断80端口
if ($server_port = 80 ) {return 301 https://example.com$request_uri; }
#方法4,判断协议
if ($scheme = http ) {return 301 https://example.com$request_uri; }
#方法5,判断ssl附加数据
if ($ssl_protocol = "") { return 301 https://example.com$request_uri; }
#方法6,判断域名(需要和其他方法搭配)
if ($host != 'www.idzd.top') {return 301 https://example.com$request_uri; }
测试
➜ ~ curl -I http://xp.sb
HTTP/1.1 301 Moved Permanently
Server: openresty
Date: Wed, 26 Mar 2025 00:05:42 GMT
Content-Type: text/html
Content-Length: 166
Connection: keep-alive
Location: https://xp.sb/