Nginx将所有子域重定向到主域

qkf9rpyu  于 2023-01-16  发布在  Nginx
关注(0)|答案(2)|浏览(191)

我正在尝试将所有子域重定向到我的主域,但目前为止还不起作用。以下是我的操作方法:

server {
    listen         [::]:80;
    server_name *.example.com;
    return 301 $scheme://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.com.key;

        #enables all versions of TLS, but not SSLv2 or 3 which are weak and now deprecated.
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

        #Disables all weak ciphers
        ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECD$

        ssl_prefer_server_ciphers on;

        root /var/www/html;
        index index.html;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }
}

但是,当我键入www.example.com时,它会重定向到https://www.example.com,我如何将所有子域重定向到https://example.com

bxjv4tth

bxjv4tth1#

如果您在同一台服务器上有多个站点,并且其中一个主站点是www.example.com

# main domain:

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

对于所有子域,错误或拼写错误可重定向到www:

server {
    listen 80;
    server_name *.example.com;
    return 301 http://www.example.com;
}

Nginx将首先检查www.example.com,如果不匹配,所有其他子域将被重定向到www.one。

w7t8yxp5

w7t8yxp52#

您可以简单地创建一个默认服务器,将所有内容重定向到https://example.com,如下所示:

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

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

所有未找到匹配服务器的传入请求都将由默认服务器提供服务,默认服务器会将它们重定向到正确的域。

相关问题