Setting up redirects www → non-www and HTTP → HTTPS at the same time, I ran into duplication issue that I fail to overcome.
On my domain—let it be example.com
—I have a website with primary name another.example.com
. I want the requests to example.com
, www.example.com
, and www.another.example.com
to be redirected to another.example.com
, and all HTTP requests to be redirected to HTTPS at the same time; I also want to support HTTP/2 and IPv6.
I have no issue with getting this to work, but I fail to get rid of duplicating a substantial part of configuration file (namely HTTPS certificate settings). All attempts to reduce duplication cause one or more or all redirects to stop working (sometimes along with HTTP/2).
Please take a look at the config and suggest how to clean it up:
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;
}