![无法使用 Nginx 和 Cloudflare 从非 www 重定向到 www](https://linux22.com/image/779142/%E6%97%A0%E6%B3%95%E4%BD%BF%E7%94%A8%20Nginx%20%E5%92%8C%20Cloudflare%20%E4%BB%8E%E9%9D%9E%20www%20%E9%87%8D%E5%AE%9A%E5%90%91%E5%88%B0%20www.png)
我对 Nginx 和 CF 非常陌生,我已经将我的网站部署到example.com
,它运行良好,并且也重定向到 https。但我想www
一直重定向到。现在如果我输入,example.com
它不会重定向到www
。
我还为我的网站设置了 Cloudflare。
寻找解决方案后,在 Digital Ocean 中找到了一个解决方案,它说要替换这个:
server {
if ($host = www.example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name example.com www.example.com;
listen 80;
return 404; # managed by Certbot
}
更改为:
server {
if ($host = www.example.com) {
return 301 https://www.example.com$request_uri;
} # managed by Certbot
if ($host = example.com) {
return 301 https://www.example.com$request_uri;
} # managed by Certbot
server_name example.com www.example.com;
listen 80;
return 404; # managed by Certbot
}
但它不起作用。这是怎么回事?
以下是该网站的完整 nginx 配置:
server {
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com www.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $http_cf_connecting_ip;
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
real_ip_header CF-Connecting-IP;
}
server {
if ($host = www.example.com) {
return 301 https://www.example.com$request_uri;
} # managed by Certbot
if ($host = example.com) {
return 301 https://www.example.com$request_uri;
} # managed by Certbot
server_name example.com www.example.com;
listen 80;
return 404; # managed by Certbot
}
答案1
不幸的是,Certbot 在 nginx 上以有问题的方式实现了重定向。
在 Nginx 反向代理中从 www 重定向到无 www是类似的情况,请参考答案了解您应该使用的配置。
答案2
您提到客户端被重定向到 HTTPS,从他们从 Cloudflare 获取 TLS 加密来看,您的 Nginx 并未为此进行配置。
该块仅响应example.com:
server {
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com; # Removed the www subdomain
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $http_cf_connecting_ip;
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
real_ip_header CF-Connecting-IP;
}
此块将删除 www,使 301 永久重定向到https://example.com:
server {
server_name www.example.com;
listen 80;
return 301 https://example.com$request_uri;
}
现在您可以在单个块上设置所有内容,但是,我建议您设置 TLS 并使用顶部块开始监听另一个端口(通常为 443)上的 TLS 连接。