在 nginx 中将 https://www.example.com 重定向到 https://example.com

在 nginx 中将 https://www.example.com 重定向到 https://example.com

我已为 domain.com 颁发了 SSL。现在这些 URL 工作正常:

http://www.example.com -> https://example.com
http://example.com -> https://example.com
https://example.com

但是当使用https://www.example.com它显示安全证书错误如下:

There is a problem with this website’s security certificate.

我的 nginx 配置(site-available/example.com)如下:

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

server {
    listen 80;
    server_name  example.com;
    return       301 https://example.com$request_uri;
}
server {
    listen 443;
    server_name example.com;
    ssl on;
    ssl_certificate /etc/ssl/certs/example_com.crt;
    ssl_certificate_key /etc/ssl/private/example.key;
    ...
    ...
    ...

我如何重定向 URLhttps://www.example.comhttps://example.com在这个配置文件中

答案1

创建永久重定向:

server {
      charset utf-8;
      listen 80;
      listen 443 ssl;
      server_name www.example.com;

      rewrite ^/(.*) https://example.com/$1 permanent;
}

server {
      charset utf-8;
      listen 80;
      listen 443 ssl;
      server_name example.com;

      location / {
      # this serves the actual content ...
      }

     if ($ssl_protocol = "") {
       rewrite ^/(.*) https://$server_name/$1 permanent;
     }
}

答案2

我编辑了我的配置如下:

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

server {
    listen 443;
    server_name example.com *.example.com;

<-your_other_site_configurations->
...
...

现在它运行正常!希望它也能帮助其他人!

相关内容