nginx リダイレクト設定の重複を回避しますか?

nginx リダイレクト設定の重複を回避しますか?

リダイレクトの設定www非wwwそしてウェブ翻訳同時に、克服できない重複の問題に遭遇しました。

私のドメインには、example.comプライマリ名 の Web サイトがあります。 、、へのanother.example.comリクエストを にリダイレクトし、すべての HTTP リクエストを同時に HTTPS にリダイレクトしたいと考えています。また、HTTP/2 と IPv6 もサポートしたいと考えています。example.comwww.example.comwww.another.example.comanother.example.com

これを動作させることに問題はありませんが、構成ファイルの大部分 (つまり、HTTPS 証明書設定) の重複を取り除くことができません。重複を減らすためのすべての試みは、1 つ以上またはすべてのリダイレクトの動作を停止させます (場合によっては 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;
        }
    }
}

関連情報