
設定重定向萬維網→非 www和HTTP協定→HTTPS同時,我遇到了無法克服的重複問題。
在我的網域上(不管怎樣example.com
)我有一個主要名稱為 的網站another.example.com
。我希望將example.com
、www.example.com
、 和 的請求www.another.example.com
重新導向到another.example.com
,並且將所有 HTTP 請求同時重新導向到 HTTPS ;我還想支援 HTTP/2 和 IPv6。
我對此工作沒有任何問題,但我無法擺脫設定檔的大部分重複(即 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;
}
}
}