从 www 重定向到非 www Nginx 时出现重定向循环

从 www 重定向到非 www Nginx 时出现重定向循环

我在 Nginx 服务器上建立了一个带有 Google 域名的网站。我想将所有链接重定向到安全且非 www 的链接。例如:

http://example.com       ->  https://example.com
http://www.example.com   ->  https://example.com
https://www.example.com  ->  https://example.com

每当我访问网站时,页面都会显示redirected you too many times.

这是我的nginx.conf

###### Redirect to secure site
server {
  listen       80;
  listen       [::]:80;
  server_name example.com www.example.com;
  return 301 https://example.com$request_uri;
}

###### Redirect to non www site
server {
  listen [::]:443 ssl http2;
  listen 443 ssl http2;

  server_name www.example.com;

  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

  return 301 https://example.com$request_uri;
}

###### Main config for secure and non www site
server {
  listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot
  listen 443 http2 ssl;

  server_name example.com;

  ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

  root /usr/share/nginx/example.com;
}

答案1

原来是我在设置 WordPress 地址 (URL) 时出错了。我将其设置www.example.com为 而不是example.com。当我更正 URL 地址时,现在一切都正常了。

没有问题nginx.conf

相关内容