Server blocks can be used to configure and host more than one domain on a single server.
Prerequisites
Make sure Nginx is installed and can be started without any issues. For this guide we will be:
- using a non-root user with
sudo
access. - setting up Nginx to run two sites, site1.com and site2.com with one page (index.html) each.
We will also be assuming the DNS has been configured already.
A simple A record pointing to the server’s IP address is all that is needed for this guide.
Set Up Document Root Directories and Their Index Pages
Nginx has one server block enabled by default and it is configured to serve documents from /var/www/html
.
For each site we need to create directories with specific permissions and ownership as follows.
|
|
Permissions and ownership of files/folders should be adjusted based on the technology and configuration.
Now that the directories have been created, we can create index.html files so we can test our configuration.
Edit /var/www/site1.com/index.html
:
|
|
Edit /var/www/site2.com/index.html
:
|
|
Create Server Block Files
Nginx contains one server block called default which we will use as a template.
|
|
Update /etc/nginx/sites-available/site1.com
:
|
|
Update /etc/nginx/sites-available/site2.com
:
|
|
Enable Server Blocks and Restart Nginx
There are two directories under /etc/nginx/
that hold the server block files. One is for available sites and the second is for enabled sites. The server block files we created in the step above are in the available-sites folder so now we need to create links for them to enable them.
|
|
It is good practice to enable sites by creating links in the enabled-sites folder so that it is easier to manage and remove sites without losing the configuration files.
Now that our server block files are linked to the enabled-sites folder, we can test our Nginx configuration and restart Nginx.
|
|
To test the nginx configuration, run
sudo nginx -t
.
Disable default
Server Block and Test Configuration
There should be three files in /etc/nginx/sites-available
directory and links to the same files in /etc/nginx/sites-enabled
.
We need to remove the default
server block from the enabled sites folder.
|
|
Now we have 2 server blocks enabled:
site1.com
which will respond tosite1.com
andwww.site1.com
site2.com
which will respond tosite2.com
andwww.site2.com