如何配置nginx重定向到https ...除了一个目录
How to configure nginx to redirect to https ... except for one directory
我正在设置一个 nginx 网络服务器来支持多个虚拟主机。按照最佳实践,我希望将任何 http:// 请求重定向到等效的 https://.
这很简单,但我想有一个例外:对 /.well-known/ 下的任何文件的任何请求都应作为 http 提供,而无需 https 重定向。任何使用过 LetsEncrypt 的人都会认出“.well-known”目录是 LetsEncrypt 寻找验证文件的地方。这些必须通过 HTTP 提供。
到目前为止,我有一个 'default' 的配置文件,如下所示:
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
.
我尝试了很多不同的方法——更改位置规则的顺序等——但我似乎仍然无法获得我想要的行为。
我做错了什么?
如果您启用了 HSTS(HTTP 严格传输安全),您将无法 "turn off" 某些页面的 https,因为整个域都将强制使用 https。您也许可以使用一些复杂的 HTTP 302 重定向设置来完成这项工作,但我不确定您为什么要这样做。如果您的 .well-known 目录是通过 HTTPS 提供的,那么 Let's Encrypt 将可以毫无问题地更新证书。
我正在设置一个 nginx 网络服务器来支持多个虚拟主机。按照最佳实践,我希望将任何 http:// 请求重定向到等效的 https://.
这很简单,但我想有一个例外:对 /.well-known/ 下的任何文件的任何请求都应作为 http 提供,而无需 https 重定向。任何使用过 LetsEncrypt 的人都会认出“.well-known”目录是 LetsEncrypt 寻找验证文件的地方。这些必须通过 HTTP 提供。
到目前为止,我有一个 'default' 的配置文件,如下所示:
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
.
我尝试了很多不同的方法——更改位置规则的顺序等——但我似乎仍然无法获得我想要的行为。
我做错了什么?
如果您启用了 HSTS(HTTP 严格传输安全),您将无法 "turn off" 某些页面的 https,因为整个域都将强制使用 https。您也许可以使用一些复杂的 HTTP 302 重定向设置来完成这项工作,但我不确定您为什么要这样做。如果您的 .well-known 目录是通过 HTTPS 提供的,那么 Let's Encrypt 将可以毫无问题地更新证书。