Serve multiple subdomains with different root single config nginx

Revision history
Tags: nginx

This is a configuration I’ve been very happy with for serving multiple subdomains with different content with a single nginx configuration file.

# Subdomains
server {
        listen 80; 
        listen 443 ssl;
        server_name "~^(?<subdomain>\w+)\.example\.com$";
        ssl_certificate         /etc/letsencrypt/live/;
        ssl_certificate_key     /etc/letsencrypt/live/;
        if ($https != 'on') {
                return 301 https://$$request_uri;
        location / { 
                root /var/www/$subdomain;
                index index.html;
        access_log /var/log/nginx/;
        error_log  /var/log/nginx/ error;

If you have any comments or feedback, please send me an e-mail. (stig at stigok dotcom).

Did you find any typos, incorrect information, or have something to add? Then please propose a change to this post.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.