If you have many domains and you are looking for a more generic approach without loosing performance and without listing all domains all the time, check this.
How it works?
- listen to 80 and redirect all http to https - including
http://www.
which will go to https://www.
- listen to 433, but only on
www
server names and redirect to non-www
using regular expression
- listen to 433 for each of your non-
www
server name - this is where all the traffic will end up
Is it fast?
Yes! Even though we use RegExp, it's only in the www
-versions block which returns 301. So all normal traffic will be handled without any additional processing cost.
# Redirect everything to HTTPS (including "www")
server {
listen 80 default_server;
listen [::]:80 default_server;
return 301 https://$host$request_uri;
}
# Redirect away from "www" versions:
server {
listen [::]:443 ssl http2;
listen 443 ssl http2;
server_name www.example-1.com
www.example-2.com
www.example-3.com;
# using generic "www" removal // https://stackoverflow.com/questions/11323735/nginx-remove-www-and-respond-to-both/45676731#45676731
if ( $host ~ ^www\.(.+)$ ) {
set $without_www $1;
rewrite ^ $scheme://$without_www$uri permanent;
}
# SSL settings:
ssl_certificate /etc/letsencrypt/live/example/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example/privkey.pem; # managed by Certbot
}
# And finally one "server" block for each of your domains
server {
listen [::]:443 ssl http2;
listen 443 ssl http2;
server_name example-1.com;
# SSL settings, etc...
}
server {
server_name example-2.com;
# ... listen, ssl, etc...
}
server {
server_name example-3.com;
# ... etc
}
PS: if you need help with SSL setup, checkout Mozilla SSL Configuration Generator:
https://ssl-config.mozilla.org/