Serving Multiple Websites with Nginx

by Troy Scott

2014/02/02

Recently i moved my troyscott.ca site from a Shared Hosting Provider to a Digital Ocean Droplet.   Because i had built the web site using Jekyll the migration was very quick and painless. Setting up the Nginx webserver for just one site was very straightforward. I just reviewed the Nginx Beginner's Guide and the site was up and running in no time.

To get the single site up and running i just navigated to /etc/nginx/sites-available and copied the default file to default.bk and then created a very simple config file (default):


server {
    location / {
        root /home/troyscott/public;
    }
}

To add a second site the configuration was a little more involved. For each new site you may want to create a new user account on the server with its own home directory. This is useful if different people in your company or at home are maintaining the site. The new nginx config looks like this (you need to be root or use sudo to edit the file):

server {
    listen 80;
    server_name firstsite.com;
    root /home/firstsite/public;
    index index.html;

    expires 1d;
}

server {
    listen 80;
    server_name secondsite.com;
    root /home/secondsite/public;
    index index.html;

    expires 1d;
}

This examples are very basic and are for static sites. If you have a lot of websites and complex configurations you will probably want to create multiple configuration files (firstsite.conf, secondsite.conf) in the sites available folder. In this case you will have to add symlinks to these files in the sites-enabled folder.

Once you have completed the configuration run the following nginx command to reload the configuration file:

sudo nginx -s reload

If there are no errors in the config files you can navigate to the sites.