Skip to content

Route Based on TLS SNI in Nginx

Context

Users want to host two or more website with different domain name on one VM using nginx.

Solution

Nginx supports to route based on the TLS SNI, with this capability, it allow us to achieve the above goal.

Here are the steps to configure Nginx to route based on the TLS Nginx. 1. edit /etc/nginx/nginx.conf

Adding a new section stream with the following content,

Nginx Configuration File
# other configuration
stream {
     map $ssl_preread_server_name $backend_name {
        web1domain web1;
        web2domain web2;
        default web1;
     }

     upstream web1 {
         server 127.0.0.1:80;
     }

     upstream web2 {
         server 127.0.0.1:8080;
     }


     server {
         listen 443 reuseport;
         listen [::]:443 reuseport;
         proxy_pass  $backend_name;
         ssl_preread on;
     }
}

# other configuration

  1. create site configuration web1 and web2 under /etc/nginx/sites-available/.

    For example,

    • web1
    Nginx Configuration File
    server {
      listen 127.0.0.1:80;
      server_name web1domain;
    
      root /var/www/web1root;
      index index.php index.html index.htm;
    }
    
    • web2
    Nginx Configuration File
    server {
      listen 127.0.0.1:8080;
      server_name web2domain;
    
      root /var/www/web2root;
      index index.php index.html index.htm;
    }
    
  2. create symbolic link for web1 and web2 to /etc/nginx/sites-enabled