Nginx 上 www 到非 www 的重定向不起作用

Nginx 上 www 到非 www 的重定向不起作用

我的 下有以下配置/etc/nginx/sites-available/example.com。我需要将 HTTP 流量重定向到 HTTPS,将 WWW 重定向到非 www。但由于某种原因,WWW 到非 WWW 的重定向不起作用。清除浏览器缓存以进行测试...

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

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

    root /var/www/html/example.com;
    index index.html index.htm index.php index.nginx-debian.html;

    location / {
        proxy_pass http://localhost:8000;
        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;
    }

    location /wordpress/ {
        rewrite ^/wordpress/wp-json/(.*?)$ /wordpress/index.php?rest_route=/$1 last;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location /wordpress/wp-content/uploads {
        add_header X-Robots_tag "index, follow";
        if ($request_uri ~* ".(eot|woff2|woff|ttf|ico|css|js|gif|jpe?g|png|svg|mp4|avi|flv|wmv|mov|ogv|m4p|m4v|3gp|pdf)$") {
            expires 365d;
            access_log off;
            add_header Pragma public;
            add_header Cache-Control "public";
            break;
        }
        location ~ \.php$ {
            deny all;
        }
    }

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

    location ~ /\.ht {
        deny all;
    }

    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
}

答案1

http://www.example.com您拥有的是从到 的重定向https://example.com

https://www.example.com此外,您还需要从到 的重定向example.com,并带有匹配的证书。

相关内容