«

Nginx配置HTTPS后http强制跳转301完整写法

时间:2026-11-15 07:12     作者:emer     分类: Nginx


前言

站点启用 HTTPS 后,用户访问 http:// 仍走明文,需要自动跳转到 https://。301 永久跳转传递 SEO 权重,写法要在 80 端口 server 块完成。本文讲解标准 301 跳转、保留路径参数、与 443 块配合和常见坑。

操作步骤

1. 80 端口块整站跳转 HTTPS

server {
    listen 80;
    server_name www.example.com;
    return 301 https://$host$request_uri;
}

2. 443 端口块处理业务

server {
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate cert.pem;
    ssl_certificate_key cert.key;
    root /var/www/html;
    index index.html;
}

3. 带端口或特定路径(可选例外)

location /api/ {
    return 301 https://$host$request_uri;
}

4. 保留查询参数

$request_uri 自动带路径和 ? 参数,无需额外处理。

5. 校验并重载

nginx -t
nginx -s reload

6. 验证跳转

curl -I http://www.example.com

应返回 301 且 Location 为 https。

常见坑

  1. 用 rewrite 比 return 开销大,优先 return 301。
  2. 漏写 $request_uri,跳转后丢失路径和参数。
  3. 两个 server 块 server_name 不一致,匹配不到。
  4. 443 块没配证书,跳转后仍报错。
  5. 循环跳转:443 块里又跳回 https 自身。
  6. CDN 已做跳转,源站重复跳转导致多重重定向。
  7. http 与 https cookie 域不同导致登录态丢失。

总结

80 端口 server 块 return 301 https://$host$request_uri,443 块放业务与证书,$request_uri 保留路径参数。用 curl -I 验证 301。避免循环跳转和多重重定向,CDN 已处理时源站不重复配。

遇到问题加QQ23979811 协助处理

标签: Nginx HTTPS HTTP 301跳转