Add multiple sites to Nginx server
Once the nginx installation is complete then you might want to add multiple domains/subdomain/host on one server. You got to the right tutorial, we will discuss nginx configurations used to add domains.
The default configuration file for Nginx is /etc/nginx/nginx.conf. You can add domains to this configuration but it will become harder to manage. So, it is recommended to add another configuration file (in /etc/nginx/sites-available
directory) and add a new domain to it.
How to add a domain to nginx?
1. Start by creating a new configuration file in sites available directory. Name the configuration file with the domain name in it for quick identification.
$ sudo touch /etc/nginx/sites-available/example-domain.com.conf
2. Open the settings file in a text editor.
$ sudo vi /etc/nginx/sites-available/example-domain.com.conf
3. We set the server directive and tell Nginx that this configuration maps to all domain requests that match example-domain.com over port 80.
server {
listen 80;
listen [::]:80;
server_name example-domain.com www.example-domain.com;
}
4. Next configuration steps is to tell nginx which directory should Nginx serve content from. Additionally, we need to tell Nginx what files it should serve by default if none are supplied (home/index page). Put these lines underneath the server name, and between the server curl brackets.
root /var/www/example-domain.com/public_html;
index index.html index.htm;
5. Now, you add an extra touch up to instruct Nginx to try serving the request as a file. Try a directory instead of a file if it doesn't exist; otherwise, display a 404
Page Not Found message.
location / {
try_files $uri $uri/ =404;
}
6. Review and save the configuration file.
server {
listen 80;
listen [::]:80;
server_name example-domain.com www.example-domain.com;
root /var/www/example-domain.com/public_html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
7. Create the web root directory.
$ sudo mkdir -p /var/www/example-domain.com/public_html
Verify our configuration, then launch Nginx.
It is a recommended practice to test new configurations before loading them to the production server because a single syntax mistake will prevent the Nginx service from running, which will prevent users from accessing your website. You can use the following command to do so.
$ sudo nginx -t -c /etc/nginx/sites-available/example-domain.com.conf
Enable the site if no issues were discovered. In order to accomplish this, we must build a symbolic link between the site configuration file and the sites-enabled directory using the following command:
$ sudo ln -s /etc/nginx/sites-available/example-domain.com.conf /etc/nginx/sites-enabled/example-domain.com.conf
Finally, Start/Restart/Reload the server to load the changes:
$ sudo systemctl restart nginx
or
$ sudo service nginx restart