nginx 仅将non-www重定向到www,保留其他子域不变(忽略子域)

nnsrf1az  于 2023-02-07  发布在  Nginx
关注(0)|答案(1)|浏览(121)

我尝试实现的目标(仅将非www重定向到www -忽略所有子域)

example.com > https://www.example.com
example.com/query-string > https://www.example.com/query-string
http://example.com > https://www.example.com
https://example.com > https://www.example.com
es.example.com > https://es.example.com
http://es.example.com > https://es.example.com
http://es.example.com/query-string > https://es.example.com/query-string
...

我的版本是1.22.1。
目前为止我得到的是:

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

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

        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key     /etc/letsencrypt/live/example.com/key.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/example.com/ca.pem;
        ssl_stapling_verify on;

        server_name example.com;
        #return 301 https://www.example.com$request_uri;
        return 301 https://www.$host$request_uri;
}

server {
    server_name www.example.com;
    access_log /var/log/nginx/example.com.access.log rt_cache;
    error_log /var/log/nginx/example.com.error.log;
    root /var/www/example.com/htdocs;
    index index.php index.html index.htm;
    include ...
}

第二个服务器模块不工作。这

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

不起作用,因为它将所有子域重定向到www(https://de.example.com > https://www.example.com
这个

return 301 https://www.$host$request_uri;

不工作,即使它redirs非www做www版本,但在同一时间,它redirs所有子域到www.subdomain(https://de.example.com > https://www.de.example.com)。
我认为问题出在第二个服务器块的server_name上。有什么办法解决这个问题吗?

0g0grzrc

0g0grzrc1#

尝试使用此配置:

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

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

server {
       listen 80;
       server_name "~(?<!www)\.example\.com$";

       return 301 https://$host$request_uri;
}

server {
       listen 443 ssl;
       server_name example.com;

       return 301 $scheme://www.$host$request_uri;
}

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

       ...
}

相关问题