无法从 https 链接 nginx 中删除 www

Can't remove www from https links nginx

我想做什么

我想将所有重定向到 https 非 www

http://mytestwebsite.com      > https://mytestwebsite.com
http://www.mytestwebsite.com  > https://mytestwebsite.com
https://www.mytestwebsite.com > https://mytestwebsite.com

我试过了

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name www.mytestwebsite.com mytestwebsite.com;

    return 301 https://mytestwebsite.com$request_uri;
}

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

    if ($host = www.mytestwebsite.com) {
        return 301 https://mytestwebsite.com$request_uri;
    }

    server_name www.mytestwebsite.com mytestwebsite.com;
    ssl_certificate /home/mysite/ssl.cert;
    ssl_certificate_key /home/mysite/ssl.key;
    # SSL configuration
    # Other configurations
}

server {
         server_name "~^www\.(.*)$" ;
         return 301 $scheme://$request_uri ;
}

有了这个,一切正常,除了

https://www.mytestwebsite.com > https://mytestwebsite.com

我总是https://www.mytestwebsite.com......

我尝试了很多来自 Whosebug、google 等的解决方案,但没有任何效果。 https 总是有 www...

如何从 https 链接中删除 www?

首先检查您的 dns 记录 是否配置为 mytestwebsite.com。如果不是,则通过域提供商仪表板添加 A 记录

那么你可以拥有这样的东西:

server {
  #listen and all other stuff

  server_name www.mytestwebsite.com;

  location / {
    return 301 https://mytestwebsite.com/$uri;
  }
}

它会做的是,如果有任何请求发送到 www.mytestwebsite.com,它将是 301 Moved Permanentlymytestwebsite.com