要将HTTP请求自动重定向到HTTPS,可以通过以下几种方式配置Nginx:
server {
listen 80;
server_name example.com www.example.com;
# 301永久重定向到HTTPS
return 301 https://$host$request_uri;
# 或者使用rewrite规则
# rewrite ^ https://$host$request_uri permanent;
}
server {
listen 443 ssl;
server_name example.com www.example.com;
# SSL配置
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 其他HTTPS配置...
}
server {
listen 80;
server_name example.com www.example.com;
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
# 其他配置...
}
server {
listen 443 ssl;
server_name example.com www.example.com;
# SSL配置
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 启用HSTS (HTTP Strict Transport Security)
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 其他HTTPS配置...
}
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
301 vs 302重定向:
SSL证书配置:
HSTS安全考虑:
测试重定向:
curl -I http://example.com
应返回301状态码和Location头部指向HTTPS地址
配置检查:
nginx -t
测试配置无误后重载Nginx:
nginx -s reload
以上配置可根据实际需求进行调整,确保所有HTTP流量都安全地重定向到HTTPS。