【问题标题】:How to configure nginx to redirect to https ... except for one directory如何配置nginx重定向到https ...除了一个目录
【发布时间】:2017-07-09 00:17:19
【问题描述】:

我正在设置一个 nginx 网络服务器来支持多个虚拟主机。按照最佳实践,我希望将任何 http:// 请求重定向到等效的 https://。

这很简单,但我想有一个例外:对 /.well-known/ 下的任何文件的任何请求都应作为 http 提供,而不需要 https 重定向。任何使用过 LetsEncrypt 的人都会将“.well-known”目录识别为 LetsEncrypt 查找验证文件的位置。这些必须通过 HTTP 提供。

到目前为止,我有一个“默认”的配置文件,如下所示:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    root /var/www/default/www;
    index index.php index.html index.htm;
    location ^~ /.well-known/ {
        allow all;
    }
    location / {
        return 301 https://$host$request_uri;
    }
}

然后,对于每个虚拟主机,我都有一个单独的文件,如下所示:

server {
    listen 443 ssl;
    server_name myexamplevirtualhost.com;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    # lots more SSL-related stuff
    location / {
        try_files $uri $uri/ =404;
    }
}

server {
    listen 80;
    server_name myexamplevirtualhost.com;
    location / {
        return 301 https://$server_name$request_uri;
    }
    location /.well-known/ { }
}

如果我请求,例如,http://myexamplevirtualhost.com/,我会被重定向到https://myexamplevirtualhost.com/——这就是我想要的。同样,对https://myexamplevirtualhost.com/ 的直接请求也可以正常工作。

但是,如果我尝试:http://myexamplevirtualhost.com/.well-known/foo123,而不是服务器简单地提供 http://myexamplevirtualhost.com/.well-known/foo123(这是目标),它会重定向到 https://myexamplevirtualhost.com/.well-known/foo123

我尝试了很多不同的方法——更改位置规则的顺序等——但我似乎仍然无法获得我想要的行为。

我做错了什么?

【问题讨论】:

  • 你有 HTTP 严格的传输安全吗?
  • 是的,各个域的服务器块包括:add_header Strict-Transport-Security max-age=15768000 嗯。这可能是我的问题。

标签: http redirect nginx https lets-encrypt


【解决方案1】:

如果您启用了 HSTS(HTTP 严格传输安全),您将无法“关闭”某些页面的 https,因为 https 将被强制用于整个域。您也许可以使用一些复杂的 HTTP 302 重定向设置来完成这项工作,但我不确定您为什么要这样做。如果您的 .well-known 目录是通过 HTTPS 提供的,Let's Encrypt 更新证书将毫无问题。

【讨论】:

  • 我相信使用 HSTS 确实是问题所在,正如您和 Richard Smith 所发现的那样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-02
  • 2017-09-20
  • 2012-01-15
  • 1970-01-01
相关资源
最近更新 更多