在多个 Nginx 站点上使用 Https 强制 WWW 为非 www

在多个 Nginx 站点上使用 Https 强制 WWW 为非 www

我有多个网站想要重定向到非 www https。目前,一切似乎都很好,除了当你手动输入https://www.example.com对于任何网站,它都不会重定向,您会被带到按字母顺序排列的第一个网站。尝试这样做时,我遇到了各种不同的错误。我当前的设置包括:主网站

server {
    listen 80;
    listen [::]:80 ipv6only=on;
    server_name example.com www.example.com;
    rewrite ^ https://example.com$request_uri? permanent;
}
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2 default_server ipv6only=on;
}

其他所有网站

server {
    listen 80;
    server_name www.example.com example.com;
    rewrite ^ https://example.com$request_uri? permanent;
}
server {
    listen 443 ssl http2;
}

我尝试将每个网站重定向到非 www https

server {
  server_name example.com;
  listen 443 ssl http2;
}
server {
  listen       80;
  server_name  example.com www.example.com;
  return       301 https://example.com$request_uri;
}
server {
  listen 443 ssl http2;
  server_name www.example.com;
  return 301 https://example.com$request_uri;
}

答案1

我这样修复了它:

主站点:

server {
    listen 80;
    listen [::]:80 ipv6only=on;
    server_name example.com www.example.com;
    rewrite ^ https://example.com$request_uri? permanent;
}
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2 ipv6only=on;
    server_name www.example.com;
    rewrite ^ https://example.com$request_uri? permanent;
}
server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    ssl_certificate /usr/local/nginx/ssl/nginx.crt;
    ssl_certificate_key /usr/local/nginx/ssl/nginx.key;
    server_name example.com;
    root /home/example/public_html;
    index index.php;
    [... all stuff ...]
}

所有其他网站

server {
    server_name www.example.com example.com;
    rewrite ^ https://example.com$request_uri? permanent;
}
server {
    listen 443 ssl http2;
    ssl_certificate /usr/local/nginx/ssl/nginx.crt;
    ssl_certificate_key /usr/local/nginx/ssl/nginx.key;
    server_name example.com;
    root /home/example/public_html;
    index index.php;
    [... all stuff ...]
}

相关内容