避免 nginx 重定向配置重复?

避免 nginx 重定向配置重复?

设置重定向万维网非 wwwHTTPHTTPS同时,我遇到了无法克服的重复问题。

在我的域名上 — 假设example.com— 我有一个名为 的网站。我希望将对、和 的another.example.com请求重定向到,同时将所有 HTTP 请求重定向到 HTTPS;我还希望支持 HTTP/2 和 IPv6。example.comwww.example.comwww.another.example.comanother.example.com

我没有遇到任何问题,但我无法消除配置文件中大量重复的部分(即 HTTPS 证书设置)。所有减少重复的尝试都会导致一个或多个或所有重定向停止工作(有时还会伴随 HTTP/2)。

请查看配置并建议如何清理它:

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

server {
    listen 443;
    listen [::]:443;
    server_name www.another.example.com www.example.com example.com;
    return 301 https://another.example.com$request_uri;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

server {
    server_name another.example.com;
    root /usr/share/nginx/another.example.com;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    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/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

答案1

server {
    server_name another.example.com;
    root /usr/share/nginx/another.example.com;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    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/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name www.another.example.com www.example.com example.com;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
    rewrite ^/(.*)$ https://another.example.com/$1 permanent;
}
server {
    listen 80;
    listen [::]:80;
    server_name www.another.example.com www.example.com another.example.com example.com;
    location / {
        if ($host !~* ^(www)) {
          rewrite ^/(.*)$ https://another.example.com/$1 permanent;
        }
    }
}

相关内容