【问题标题】:Redirecting to SSL using nginx使用 nginx 重定向到 SSL
【发布时间】:2013-08-30 00:45:40
【问题描述】:

我在同一主机上有 http:// 和 https://,如下所示:

server {

    listen   80;
    listen   443 ssl;

    ...
    ...
}

我需要做的是将访问我商店的用户重定向到 https://。问题是我有多种语言:

https://mydomain.com/zh/shop https://mydomain.com/fr/shop 等等……

我试过了,但没用(nginx: configuration file /etc/nginx/nginx.conf test failed)

if ($server_port = 80) {
    location (en|fr)/shop {
        rewrite ^ https://$host$request_uri permanent;
    }
}

【问题讨论】:

    标签: nginx


    【解决方案1】:

    执行 301 重定向而不是使用 if 语句也更像是 NGINX 最佳实践(请参阅http://wiki.nginx.org/Pitfalls 上的服务器名称)。我使用为 SSL、Rails 和 Unicorn 配置的 nginx.conf 创建了一个要点

    https://gist.github.com/Austio/6399964

    这将是您的相关部分。

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

    【讨论】:

    • (抱歉挖了一个旧线程)为避免不良做法,我认为应该将其标记为答案。
    • 代替硬编码域名,我们可以这样做:return 301 https://$host$request_uri;
    【解决方案2】:

    或者更好的是,避免使用硬编码的服务器名称

    server {
      listen 80;
      rewrite (.*) https://$http_host$1 permanent;
    }
    

    【讨论】:

      【解决方案3】:

      为了使用正则表达式匹配locations,您需要在表达式前面加上~~*

      if ($server_port = 80) {
          location ~ (en|fr)/shop {
              rewrite ^ https://$host$request_uri permanent;
          }
      }
      

      来自documentation

      要使用正则表达式,必须使用前缀:

      1. "~" 区分大小写匹配
      2. "~*" 用于不区分大小写的匹配

      由于 nginx 不允许 location 块嵌套在 if 块内,请尝试以下配置:

      if ($server_port = 80) {
          rewrite ^/(en|fr)/shop https://$host$request_uri permanent;
      }
      

      【讨论】:

      • 您的代码出现另一个错误:重新启动 nginx: nginx: [emerg] "location" directive is not allowed here in
      • @AdamSilver:location 不能包含在 if 块内(请参阅位置的文档)。只需将重写规则更改为仅在路径以 (en|fr)/shop 开头时才重写。
      • 但是我会得到一个重定向循环!
      • @AdamSilver:你不应该。你保留你的if,但只在其中嵌套一个rewrite
      【解决方案4】:

      理想情况下,在保留尾随路径的同时避免使用 if 语句:

      server {
        listen 80;
        server_name example.com;
        rewrite (.*) https://example.com$1 permanent;
      }
      

      永久负责 301。

      【讨论】:

        【解决方案5】:

        error_page 497 的另一种方式

        server {
            listen 80;
            listen 443;
        
            ssl on;
            error_page 497  https://$host$request_uri;
            ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
            ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
        ...
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-12-22
          • 2022-01-08
          • 2016-01-31
          • 1970-01-01
          • 2016-04-02
          • 2014-11-16
          • 2015-02-26
          相关资源
          最近更新 更多