Multiple domains can be hosted on Nginx using server blocks. If you choose a VPS as your hosting platform, all your websites can reside in a single server, giving you the flexibility to take control of things yourself. This guide explains how to host multiple websites on a single server using Nginx.
Nginx is a web server. It can also be used as a reverse proxy, load balancer, mail proxy, and HTTP cache. In this article, I will explain how to use Nginx as a webserver to serve multiple websites hosted on the same server.
All our hosting configuration is done via .conf files. For clarity, I will create two separate .conf files for the two sites we host.
Creating .conf files
For the rest of this article, I assume my Nginx installation folder is /etc/nginx. I refer to this as the Nginx root folder.
Go to the Nginx root folder and locate nginx.conf file. Ensure the conf file has the below entry.
This entry says Nginx to look for configuration files in the specified location on startup. This is where we create our two configuration files to host two websites. For best practices, I would give the files the website's domain names and they must have a .conf file extension. To be specific, these are called server blocks.
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/example1.com;
index index.html;
server_name example1.com www.example1.com;
location / { try_files $uri $uri/ =404;}
}
server {
listen 80;
listen [::]:80;
root /var/www/example2.com;
index index.html;
server_name example2.com www.example2.com;
location / { try_files $uri $uri/ =404;}
}
Uploading Html and static files
Now we have to place our static file contents so the server can find them. Note that we have a root attribute in both server blocks. This root specifies the document root for each server block we created. Our next step is to navigate to /var/www/ and create two folders example1.com and example2.com. Place each site's HTML and static files in these folders.
Server block attributes explained
Now let's take a look at how each attribute in the server-block works.
After all these changes run the below command to restart the server to take the changes into effect