nginx www vhost,未重定向到非 www https:// 网站

nginx www vhost,未重定向到非 www https:// 网站

我有一个网站可以与

domain.com --> redirects to https://example.com
https://example.com --> works fine
https://www.example.com --> redirects to https://example.com --> works fine
www.example.com --> 404 error --> should redirect to https://example.com

这是我的虚拟主机,名称为 example.com

    server {
   server_name myip domain.com www.example.com;
   root /var/www/cra-myapp/myapp/LandingPage/my-default-starter/public;
   index index.html index.htm;
   location / {
   try_files $uri /index.html =404;
   }


    listen 443 ssl; # managed by Certbot
    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


}
server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


   server_name myip example.com;
    listen 80;
    return 404; # managed by Certbot


}

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

那里有什么问题?我已经生成了 SSL 配置,其中添加了一些配置块

sudo certbot --nginx -d example.com -d www.example.com

答案1

问题出在第二个server区块。

检查访问的域名是否为example.com,如果是,则重定向到https://example.com+ 原始 URL 路径。否则返回 404。

Certbot 在 nginx 配置方面做得不是很好。因此我建议您删除第二个server块并改用以下内容:

server {
    listen 80;
    server_name example.com www.example.com myip;

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

相关内容