I would like to redirect all traffic from the following domains:
http://domain.com
http://www.domain.com
http
Provide a specific server block for the naked domain along with a general default. The more-specific ones will be used first.
server {
listen 80;
listen [::]:80;
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
return 301 https://www.$host$request_uri;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com;
# omitting the rest for https://www.example.com
}
I use Let's Encrypt for my certificates so something like the following for default_server
prevents redirecting the ACME challenges (note the second wildcard server_name for handling all https://*.example.com
which don't have their own server block).
# omit server_name example.com block, same as above
server {
listen 80 default_server;
listen [::]:80 default_server;
location ~ ^/\.well-known/acme-challenge {
# LetsEncrypt
add_header Content-Type text/plain;
expires 0;
alias /var/www/html/acme/$host;
break;
}
location ~ ^/(?!\.well-known/acme-challenge) {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name *.example.com;
# omitting the rest for https://*.example.com
}
Setup certificates for the naked example.com, www.example.com and any others:
sudo certbot certonly --manual -d example.com -d www.example.com -d abc.example.com