NGINX 作为代理 - 重定向到 www

NGINX 作为代理 - 重定向到 www

现在该网站在 www 和非 www 上都可以运行。我希望它只在 www 上运行,并将所有非 www 重定向到 www。HTTP 和 HTTPS 都可以。

我有以下虚拟主机:

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




server {
        listen 443 ssl;
        server_name example.com www.example.com;
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';


        location /  {
                proxy_pass    http://localhost:3006;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }
}

我尝试改变

return 301 https://$host$request_uri;

return 301 https://www.$host$request_uri;

但它不起作用

我尝试将其更改为:return 301 https://www.example.com$request_uri;

但它也不起作用。我希望有人知道并能帮助它工作...

答案1

您更改了错误的server块。第二个server块包含:

server_name example.com www.example.com;

需要将其拆分为两个单独的server块。然后,您可以从一个块重定向到另一个块。

例如:

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

相关内容