Using a regex to specify nginx server_name

by | Apr 27, 2025 | IT Tips | 0 comments

I wanted to publish two hostnames from the one config and capture the host portion so I could redirect it correctly

Using certbot to create a single letsencrypt cert with both domains in it.

First add DNS records for both domains pointing at your webserver

sudo certbot certonly -d sitea.example.com.au -d siteb.example.com.au --nginx

Handy website to test the nginx regex's

https://regex101.com

Here is a sample nginx config

#
# The default server
#
server {
    # redirect www to host
    listen *:80;
    listen [::]:80;
    server_name ~^(sitea|siteb)\.example\.com\.au$;
    return 301 "https://$1.toggen.com.au$request_uri";
}


server {
    listen *:443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ~^(sitea|siteb)\.example\.com\.au$;
    server_tokens off;
    access_log /var/log/nginx/sitea_access.log;
    error_log /var/log/nginx/sitea_error.log;

    ssl_certificate /etc/letsencrypt/live/sitea.example.com.au/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/sitea.example.com.au/privkey.pem;

    include ssl-common.conf;
    include no-hidden.conf;

    root /var/www/ip/web;

    index index.php index.html;

    include favicon.conf;

    location / {
        try_files $uri $uri/ /getip.php;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ .php$ {
        include fastcgi_params;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/var/run/php/sitea.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /.ht {
        deny all;
    }

    location ~ /.git {
        deny all;
    }

    include gzip-common.conf;
    include cache-common.conf;
}

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.