0%

Nginx 将 http 默认跳转到 https 的方法

Nginx 将 http 默认跳转 https 的方法有多种,本文提供几种方法以作探讨。

分开处理 http 请求和 https 请求

使 Nginx 在接收到 http 请求时自动返回 307 状态码(永久重定向并且不丢失POST数据)。

1
2
3
4
5
6
7
8
9
10
server {
server_name example.com;
listen 80;
return 307 https://$host$request_uri;
}

server {
server_name example.com;
listen 443 ssl;
}

//Nginx 的497状态码(经测试,该方法无效)

497状态码的解释是497 - normal request was sent to HTTPS。所以指定 497 状态码时跳转到 https 即可。

1
2
3
4
5
6
7
server {
server_name example.com;
listen 80;
listen 443 ssl;

error_page 497 https://$host$request_uri;
}

Nginx 中执行判断

1
2
3
if ($scheme != "https") {
rewrite ^ https://$host$request_uri permanent;
}

上述几种方法都可以成功将 http 请求跳转到 https,不过本人推荐第二种方式,配置简单并且符合规范。