How to host multiple websites on Linux with nginx
If you have a web server you may want to host several different sites on it. This is solved by making nginx serve different directories depending on the host name included in the request headers.
Create the new site
Add another directory for your new site:
$ mkdir /var/www/newsite.com
Give it some basic content:
$ echo "Hello World!" > /var/www/newsite.com/index.php
$ chmod -R 755 /var/www/testsite.com
Configure nginx to serve the site
To make nginx serve the site, we need to create a new config file for it.
Let’s get started on the config file by copying nginx’ default configuration to a new file:
$ cp /etc/nginx/sites-available/default /etc/nginx/sites-available/newsite.com.conf
In the server block of the configuration file, you’ll find a server_name directive:
server_name _;
Replace the underscore with the names you want this site to respond to:
server_name newsite.com www.newsite.com;
And set the correct server root:
root /var/www/testsite.com;
Enable and test the changes
To enable the changes, link the configuration file to the sites-enabled directory:
$ ln -s /etc/nginx/sites-available/newsite.com.conf /etc/nginx/sites-enabled/newsite.com.conf
Before you reload nginx, it’s always good to test that the configuration file will work. Otherwise you’ll get some downtime if the configuration is wrong.
$ nginx -t
nginx: the configuration file /etc/nginx-sp/nginx.conf syntax is ok
nginx: configuration file /etc/nginx-sp/nginx.conf test is successful
If it’s successful, go ahead and reload nginx:
$ systemctl reload nginx
Now you can test your configuration by connecting to your server from a web-browser with the right domain name. If you’re using a name you can’t point through DNS, edit your hostfile to point the domain to your server.