Nginx https 和非 www 导致许多重定向循环

Nginx https 和非 www 导致许多重定向循环

我正在尝试做以下事情

  • 强制在我的网址中添加 www.
  • 301 重定向至 https

当我访问 www.example.com 时,出现过多重定向错误。当我访问 example.com 时,一切正常。

不确定我哪里错了。下面是我的服务器块代码。

server {
    server_name  example.com www.example.com;
    return 301 https://www.example.com$request_uri;
}    


server {
    server_name www.mydomain.com
    ...
}

答案1

以下是我如何重定向到https://www.example.com

server {
  server_name www.example.com;
  listen 443 ssl http2;

  ssl_certificate /var/lib/acme/certs/***CERT_DIRECTORY/fullchain;
  ssl_certificate_key /var/lib/acme/certs/***CERT_DIRECTORY/privkey;

  # Set up preferred protocols and ciphers. TLS1.2 is required for HTTP/2
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_prefer_server_ciphers on;
  ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5;

  // locations etc
}

# This server simply redirects the requested to the https version of the page
server {
  listen 80;
  server_name example.com www.example.com;
  return 301 https://www.example.com$request_uri;
}

server {
  listen 443 ssl http2;
  server_name example.com;

  ssl_certificate /var/lib/acme/certs/***CERT_DIRECTORY/fullchain;
  ssl_certificate_key /var/lib/acme/certs/***CERT_DIRECTORY/privkey;

  # Set up preferred protocols and ciphers. TLS1.2 is required for HTTP/2
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_prefer_server_ciphers on;
  ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5;

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

相关内容