nginx强制http跳转https需配置独立80端口server块使用return 301 https://$host$request_uri,并确保443端口server块正确启用ssl证书、hsts头及代理场景下的497错误处理。

直接在 Nginx 配置中新增一个专用于 HTTP 跳转的 server 块,而不是在已有 location 里加 return 或 rewrite —— 这样最清晰、最稳定、也最符合官方实践。
单独配置监听 80 端口的跳转 server 块
这是核心步骤。新建或编辑站点配置文件(如 /etc/nginx/conf.d/example.com.conf),添加如下内容:
- 只监听 80 端口,不启用 SSL,不写任何 location 或 proxy_pass
-
用
return 301,比 rewrite 更快、更安全,不触发正则匹配 -
目标地址写成
https://$host$request_uri:$host 自动取请求头中的 Host 值(适配多域名),$request_uri 包含完整路径和查询参数,无需拼接
示例:
server {listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
确保 443 端口的 HTTPS server 已就绪
跳转只是“指路”,真正提供服务的是 443 的 server 块。它必须满足:
使用ydata-profiling(前身为pandas-profiling)生成全面的数据质量报告,包含相关性分析、缺失值模式和基数检测。导出交互式HTML仪表板和JSON摘要。
- 明确声明
listen 443 ssl(不是ssl on,后者已过时) - 正确配置证书路径:
ssl_certificate和ssl_certificate_key - 若后端是 Node.js、Python 等应用,需加
proxy_set_header X-Forwarded-Proto $scheme;,避免重定向循环 - 建议启用 HSTS:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
代理或 CDN 场景下补充 497 错误处理
当 Nginx 前有 Cloudflare、ALB 或 Traefik 等 HTTPS 终结代理时,用户走 HTTPS,但到 Nginx 是 HTTP 请求,80 端口跳转不生效。此时需在 443 server 块内加:
同时确认代理透传了 X-Forwarded-Proto: https 头;如有下划线 Header(如 X-Forwarded-For),还需在 http 块开头加 underscores_in_headers on;。
验证与上线前检查
改完别急着 reload,按顺序确认:
- 备份原配置:
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak - 语法检测:
nginx -t,必须显示 “syntax is ok” 和 “test is successful” - 用 curl 测试:
curl -I http://example.com/test?x=1,应返回 301 且Location头含完整 HTTPS 地址 - 浏览器访问 http 地址,观察是否秒跳、地址栏是否变绿锁、参数是否保留










