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

C. *_*rto 8 redirect nginx

我正在尝试将所有子域重定向到我的主域,但到目前为止它不起作用。这是我的做法:

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
        }
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*cus 6

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

# main domain:

server {
    listen 80;
    server_name www.example.com;
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

server {
    listen 80;
    server_name *.example.com;
    return 301 http://www.example.com$fastcgi_script_name;
}
Run Code Online (Sandbox Code Playgroud)

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

  • `fastcgi_script_name`? (2认同)

rau*_*iel 5

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

\n\n
server {\n  listen      [::]:80 default_server;\n  server_name localhost;\n\n  return 301 https://example.com$request_uri;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n