这个问题曾经被问过,但是我发现没有一个可以接受的答案对我有用。
我正在使用此一般规则将所有http流量都路由到https:
# Redirect http
# ==========================================================================
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name www.example.com example.com;
return 301 https://www.example.com$request_uri;
}
# Redirect non-www / https
# ==========================================================================
server {
# ports
listen 443 ssl http2;
listen [::]:443 ssl http2;
# domain name
server_name example.com;
# ssl certificate files
ssl_certificate /etc/ssl/certs/*****.crt;
ssl_certificate_key /etc/ssl/private/*****.key;
# Redirect all non-https requests
return 301 https://www.example.com$request_uri;
}
# Primary Server
# ==========================================================================
server {
# ports
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
# domain name
server_name www.example.com;
# ssl certificate files
ssl_certificate /etc/ssl/certs/*****.crt;
ssl_certificate_key /etc/ssl/private/*****.key;
include basic.conf;
}
但是它不起作用。端口80上的每个请求都会重定向到自身并给出错误
“重定向过多”
我真的不知道该怎么办...
Nginx在群集集群上的docker容器中运行。
更新:使用以上编辑的配置,http://example.com的工作状态为301,但http://www.example.com的重定向循环中又一次运行。使用curl我可以看到http-www-Version总是总是直接重定向回自身...但是加上了尾随的斜杠...
这是curl输出:
Ignoring the response-body
* Connection #0 to host www.example.com left intact
* Issue another request to this URL: 'http://www.example.com/'
* Found bundle for host www.example.com: 0x2cf2468 [can pipeline]
* Re-using existing connection! (#0) with host www.example.com
* Connected to www.example.com (**.***.***.***) port 80 (#0)
> GET / HTTP/1.1
> Host: www.example.com
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Server: nginx
< Date: Mon, 19 Nov 2018 12:22:25 GMT
< Content-Type: text/html
< Content-Length: 162
< Connection: keep-alive
< Location: http://www.example.com/
<
* Ignoring the response-body
* Connection #0 to host www.example.com left intact
* Maximum (50) redirects followed
curl: (47) Maximum (50) redirects followed
更新#2 :我已经尝试了几种方法,但是仍然无法正常工作。奇怪的是,如果我将第一个服务器块更改为
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name www.example.com example.com;
# test 1
return 302 https://www.another-example.com;
# test 2
return 302 https://www.example.com;
}
然后在#test 1中按预期工作,并重定向到HTTPS://www.another-example.com
。并且使用#test 2给我302 HTTP://www.example.com
...就像忽略了该特定域的HTTPS一样……???