最推荐用 return 301 实现 HTTP 到 HTTPS 跳转,语法简洁高效、保留完整路径和查询参数、SEO友好;需确保 HTTPS server 块已正确配置并放行 443 端口,修改后执行 nginx -t 和 nginx -s reload 验证。

推荐写法:使用 return 301(首选)
在你的 Nginx 配置文件(如 /etc/nginx/conf.d/your-site.conf 或 /www/server/nginx/conf/vhost/域名.conf)中,添加或确认存在如下配置:
listen 80; 必须监听 HTTP 默认端口
server_name 要与 HTTPS 的 server 块保持一致(例如 example.com www.example.com)
return 301 https://$host$request_uri; —— 关键:$request_uri 包含完整路径 + 查询参数(如 /login?next=/admin),不会丢失
示例:
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
备选写法:rewrite + permanent(兼容旧版本)
如果因历史原因需用 rewrite,语法等效但稍冗余:
- 必须加 permanent 标志,等价于 301 状态码
- ^ 表示匹配任意 URI,$1 在这里不生效;应直接用 $request_uri
- 正确写法:rewrite ^ https://$host$request_uri permanent;
⚠️ 注意:不要写成 rewrite ^(.*)$ https://$host$1 permanent; —— $1 在 ^(.*)$ 中虽能捕获,但不如 $request_uri 直观可靠,且易在特殊字符下出错。
关键前提与验证要点
确保以下条件已满足,否则跳转会失败或报错:
- HTTPS 的 443 端口 server 块已正确配置(含 ssl_certificate、ssl_certificate_key 等)
- 防火墙或云服务商安全组已放行 443 端口
- 修改后执行 nginx -t 检查语法,再 nginx -s reload 生效
- 验证方式:
• curl -I http://example.com/path?x=1 → 应返回 HTTP/1.1 301 Moved Permanently 和正确的 Location 头
• 浏览器访问 http://example.com/test?a=b → 地址栏自动变为 https://...,且参数完整保留
不推荐的写法(容易踩坑)
以下方式存在明显缺陷,应避免:
- if ($scheme = http) { return 301 ... }:放在 location 内可能失效,且 if 在 server 上下文中性能较差、逻辑易混乱
- error_page 497 ...:依赖错误触发,属于“兜底方案”,非主动拦截,用户体验差
- meta refresh 或 JS 跳转:客户端跳转,延迟高、不安全、SEO 不友好、参数可能被截断
- 只用 $uri 不拼 $args:会导致 ? 后面的查询参数丢失(如 ?id=123 消失)


















