Handle multiple virtual domains on one debian host | nginx + certbot/letsencrypt

apt-get install nginx certbot python3-certbot-nginx

For every domain create a nginx file, put it into /etc/nginx/sites-available and symlinklink it into /etc/nginx/sites/enabled: /etc/nginx/sites-available/my-domain.tld

server {
     listen 80;
     listen [::]:80;
     server_name my-domain.tld www.my-domain.tld;

     root /var/www/my-domain.tld;

     index index.html index.htm;

     location / {
          try_files $uri $uri/ =404;
     }
}

Create the corresponding dirs and index.htmls (here: /var/www/my-domain.tld)

Restart your nginx:

systemctl restart nginx

Run your certbot

certbot --nginx -d my-domain.tld -d www.my-domain.tld

That touches your nginx domain files in a nice way, resulting in stuff like this:

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
server {

	server_name my-domain.tld www.my-domain.tld;

	root /var/www/my-domain.tld;
	index index.html;

	location / {
		try_files $uri $uri/ =404;
	}

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-domain.tld/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-domain.tld/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}

server {
    if ($host = www.my-domain.tld) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = my-domain.tld) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


	listen 80;
	listen [::]:80;

	server_name my-domain.tld www.my-domain.tld;
    return 404; # managed by Certbot

}

Restart your nginx and do all the certbot renewal stuff. (For beginners: certbot certs are valid for 3 months only an must be renewed.)

certbot certonly --force-renew --nginx -d my-domain.tld -d www.my-domain.tld

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.