Jnnngs
Home
About
 Admin
  9 minutes

How to configure Multiple Domains with Nginx

Configure First Domain

The default configuration file for Nginx is /etc/nginx/nginx.conf, and we’re free to add our domains to this configuration. However, it is strongly recommended not to do that.

The single, biggest reason not to combine all domains in one configuration is that it will become very unwieldy and cumbersome to maintain. Rather, it is advised to create individual configuration files for each domain, placing them in the /etc/nginx/sites-available directory. There is a default file that is created as part of the initial install, so feel free it use that or rename it to something more meaningful.

The key to then enabling the domain is to create a symbolic link to the /etc/nginx/sites-enabled directory. The default file is already included, so there is nothing to do if you have reused this file. If you have renamed it to something meaningful, then run the following line command to create the symbolic link.

sudo ln -s /etc/nginx/sites-available/MEANINGFUL_NAME /etc/nginx/sites-enabled/MEANINGFUL_NAME

NB: It is common practice to name the files with an .conf extension, although it is not required to do so

Configure Second Domain

In order to create and activate the second domain, you should copy the default (or whatever you renamed it to)  file within /etc/nginx/sites-available and amend accordingly. 

cp /etc/nginx/sites-available/default /etc/nginx/sites-available/domain_two

In order for Nginx to know which configuration file to use, it references the inbound domain against the server_name configuration within the server block. The example below:-

server {
     listen 80;
     listen [::]:80;
     server_name domain-two.com www.domain-two.com;

     root /var/www/domain-two.com/public_html;

     index index.html index.htm;

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

Following this, you need to create the symbolic link.

sudo ln -s /etc/nginx/sites-available/domain_two /etc/nginx/sites-enabled/domain_two

Start or restart the Nginx service

sudo systemctl start nginx

If Nginx is already running, reload all configuration files without stopping the service.

sudo systemctl reload nginx

Verify that Nginx is running.

sudo systemctl status nginx