【问题标题】:Redirect http to https via nginx通过 nginx 将 http 重定向到 https
【发布时间】:2025-12-09 12:50:01
【问题描述】:

我有一个完整的 nginx 版本安装:Ubuntu 16.04 上的 nginx/1.10.0 (Ubuntu) 除了 /etc/nginx/sites-enabled/default 被以下替换...

server {
    listen 443 default_server;
    server_name www.example.com;

    ssl_certificate           /etc/nginx/cert.crt;
    ssl_certificate_key       /etc/nginx/cert.key;

    ssl on;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

    location / {
        proxy_pass http://localhost:8080; # my existing apache instance
        proxy_set_header Host $host;

        # re-write redirects to http as to https, example: /home
        proxy_redirect http:// https://;
    }
}

其目的是作为在端口 8080 上运行的 http api 的 https 包装器。

我现在正在尝试这样做,以便当有人通过 http 端口 80 访问我的网站时,它会将他们重定向到 https。我已经尝试过所有其他记录在案的修复程序,主要是基于这样的......

server {
   listen 80;
   return 301 https://$host$request_uri;
}

...似乎没有任何效果,而且您​​总是会看到 WELCOME TO NGINX 页面。

【问题讨论】:

标签: nginx https


【解决方案1】:

来自this的问题,

您的配置中缺少server_name 参数。

server {
       listen         80;
       server_name    my.domain.com;
       return         301 https://$server_name$request_uri;
}

【讨论】:

  • 尝试失败。
  • 如果你在你的机器上运行它,你是否将服务器名称更改为localhost
  • 是的,我做到了。零变化。就好像端口 80 服务器配置被其他地方覆盖了一样。
  • 配置更改后是否重启了服务器?
  • 是的,并且完全重启了机器以确保 100% 确定
【解决方案2】:

原来我的工作有一个非常激进的缓存代理,无论我做什么都只是返回了默认的 nginx 页面。

固定为..

    // ...
    location / {
        proxy_pass http://localhost:8080; # my existing apache instance
        proxy_set_header Host $host;

        # re-write redirects to http as to https, example: /home
        proxy_redirect http:// https://;
        add_header Cache-Control "no-cache";
    }
}

【讨论】:

    【解决方案3】:

    我想在这里留下最近的更新,因为自从提出这个问题以来,nginx 已经发生了变化。

    您可以使用以下行重定向 http 请求:

    server {
        listen      80;
        server_name example.com;
        rewrite     ^   https://example.com$request_uri? permanent;
    }
    

    【讨论】:

      最近更新 更多