Multiple domains can be hosted on Nginx using server blocks. If you choose a VPS as your hosting platform, all your websites can reside on a single server, giving you the flexibility to take control of things yourself. This guide explains hosting 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.
For the rest of this article, I assume my Nginx installation folder is
All my hosting configuration is done via .conf files. For clarity, I will create two separate
Go to the Nginx root folder and locate
This entry says Nginx to look for configuration files in the specified location on startup. That is where I create two configuration files to host two websites.
The domains I want to host are
Create
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;}
}
Create
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;}
}
Note that I have a root attribute in both server blocks. That root specifies the document root for each server block we create.
In other words, the root attribute defines where the NGINX looks for hosted files. I need to create two directories,
Now I have to place my static file contents so the server can find them. The next step is to navigate
to
After all these changes, run the below command to restart the server to take the changes into effect.
Now let's take a look at how each attribute in the server-block works.