我将此 nginx 服务器配置为缓存/反向代理example.com
,www.example.com
从 mysource.example.com 获取数据
它在浏览器中似乎工作正常,但我注意到谷歌排名显着下降,当我用 wget 测试 URL 时,我得到一个无限循环。
# test without www , getting infinite loop
wget --header="Host: example.com" http://[SERVER IP]/file.html
Location: https://www.example.com/file.html [following]
--2020-02-07 21:43:14-- https://www.example.com/file.html
Reusing existing connection to www.example.com:443.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://www.example.com/file.html [following]
20 redirections exceeded.
^^^ RIGHT HERE !!!
# but with www it works OK:
wget --header="Host: www.example.com" http://[SERVER IP]/file.html
HTTP request sent, awaiting response... 200 OK
Length: 1307 (1.3K) [text/plain]
Saving to: ‘file.html’
我想我需要host
在从非 www 到 www 的重定向中指定另一个?!
或者这只是一个wget 的事情,因为它通常应该在第一次重定向时切换到 www.example.com,但它使非 www 主机不受 nginx 命令的影响?
# redirect http to https
server {
listen 80;
server_name example.com;
server_name www.example.com;
proxy_set_header Host www.example.com
return 301 https://www.example.com$request_uri;
}
# and redirect non www to www
server {
listen 443 ssl http2;
server_name example.com;
proxy_set_header Host www.example.com;
return 301 https://www.example.com$request_uri;
}
# main server, SSL
server {
listen 443 ssl http2;
server_name www.example.com;
location / {
proxy_pass http://mysource.example.com:81;
proxy_set_header Host www.example.com;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache nginx_ramdisk_cache;
}
} # end of server
问题出在你使用的方式上
wget
。通过使用:您替换wget将执行的每个请求的
Host
标头。所以:80
服务器的端口并被重定向到https://www.example.com/file.html
,443
服务器的端口,但发送Host: example.com
标头而不是Host: www.example.com
. 它被重定向到https://www.example.com/file.html
,所以,你的配置很好,只是你的测试有问题。您永远不应覆盖
Host
标头,wget会自动将其设置为 URL 中的域。