Nginx:将非 www https 重定向到 https://www

Nginx:将非 www https 重定向到 https://www

我在尝试重定向https://example.com到时遇到了一些问题https://www.example.com。它简单地给我一个重定向循环。

这是我进行更改之前的站点 nginx 配置,位于 /etc/nginx/sites-available。

有人能告诉我如何使用经过新重定向指令修改的配置正确实现重定向吗?

server {

listen 443 ssl http2;
listen [::]:443 ssl http2;

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

root /var/www/example.com/public_html;
index index.php;
server_name example.com www.example.com;

location / {
    try_files $uri $uri/ =404;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}

}

server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    return 301 https://$server_name$request_uri;
}

答案1

首先,您需要example.comserver_nameserver块的指令中删除。

其次,您需要在执行重定向的块中监听https连接。server

例如:

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name www.example.com;

    ...
}

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name example.com;

    return 301 https://www.$server_name$request_uri;
}

相关内容