首页 > 解决方案 > 无法从 https 链接 nginx 中删除 www

问题描述

我想做的事

我想将所有重定向到 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://$1$request_uri ;
}

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

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

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

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

如何从 https 链接中删除 www?

标签: nginxnginx-config

解决方案


首先检查您的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


推荐阅读