Create Virtual Host in Ubuntu Nginx Web Server

In this tutorial we are going to learn how to create virtual host in the Ubuntu Nginx Web Server. The Virtualhost is the method we use to host multiple websites on a Single Web Server.

If you haven’t installed nginx, Click on following link to learn how to install nginx on Ubuntu Server 16.04.

For this tutorial I am going to use www.example.com as the domain name for the New Nginx Virtual Host. Documentroot is going to be /var/www/example.com.

  1. Create the Documentroot

    We will start by creating the Documentroot where we put the html files of our Web Site.

    mkdir /var/www/example.com
    chgrp www-data /var/www/example.com
    
  2. Create New Virtual Host Configuration File.

    We need to add new Virtual Host Configuration File to the /etc/nginx/sites-available directory.

    vim /etc/nginx/sites-available/example.com
    

    Add Following Virtual host configuration to the configuration file.

    server {
           listen 80;
           listen [::]:80;
    
           server_name example.com www.example.com;
    
           root /var/www/example.com;
           index index.php index.html;
    
           location / {
                   try_files $uri $uri/ =404;
           }
           location ~ \.php$ {
                    include fastcgi_params;
                    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                    fastcgi_param QUERY_STRING    $query_string;
                    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
            }
    
    }
    
  3. Enable New Virtual Host

    To enable new site, we need to create a symlink to the /etc/nginx/sites-available/example.com file in the sites-enabled directory.

    ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com
    
  4. Restart Nginx Web Server

    Finally, restart the Ubuntu Nginx web server.

    systemctl restart nginx
    

To check your new website, create an index.php or index.html file inside the DocumentRoot and access the domain name from the Web Browser.

Create index.php file

vim /var/www/example.com/index.php

Add some text to the index.php file.

<?php
echo "This is Ubuntu Nginx Virtual Host for www.example.com";
?>

Open the web browser and point to the your domain name and you should see the content of your index.php file.

This way we can host as many websites as we want on Our Ubuntu Server.