Real Clear Computing

How to Create Nginx VirtualHost in Ubuntu Server

How to Create Nginx VirtualHost in Ubuntu Server

In this tutorial, we are going to learn how to create virtual hosts (Server Block) in Ubuntu Nginx Web Server.

How to Install Nginx on Ubuntu Server

Virtual hosting allows a single instance of Nginx to serve many websites, and it is the standard way of hosting multiple websites on a single computer. Each virtual host has its own Domain Name, Document Root, and a separate configuration file.

In the following demonstration, we are going to configure a virtual host for the "www.example.local" domain name (You may use your own fully qualified domain name.).

Follow These Steps to Create Nginx Virtual Hosts

First, create the document root for the contents of our site:

mkdir /var/www/example.local

Create an index.html (or index.php) file under the /var/www/example.local directory:

echo "Welcome to Ubuntu Nginx" > /var/www/example.local/index.html

Next, we need to create a new configuration file in the /etc/nginx/sites-available directory. The Configuration file must end with .conf extension. We will name it after our website name:

touch /etc/nginx/sites-available/example.local.conf

After that, open the example.local.conf and edit to match it with the following configuration:

server {
	listen 80;
	listen [::]:80;

	server_name www.example.local example.local;

	root /var/www/example.local;
	index index.html index.php;

	location / {
		try_files $uri $uri/ =404;
	}
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php-fpm.sock;
        }
}

Enable the new VirtualHost by creating a symlink to /etc/nginx/sites-enabled directory:

ln -s /etc/nginx/sites-available/example.local.conf /etc/nginx/sites-enabled/

Finally, restart the Nginx web server to ensure your settings take immediate effect:

systemctl restart nginx

That is all we need to do! The virtual host we created is capable of serving dynamic content using PHP and MySQL. You can repeat this process for any number of websites.

Nginx Sites Available and Sites Enabled Directories

In Ubuntu Nginx Server, We have sites-available and sites-enabled directories. We'd place the configuration file for each virtual host as separate files under the sites-available directory.

Nginx Sites Available and Sites Enabled Directories

However, the configuration has no effect until we create a symlink (a shortcut) from the sites-available to the sites-enabled directory.

Enable the new VirtualHost by creating a symlink to /etc/nginx/sites-enabled directory

If you want to disable the virtual host in the future, you only need to remove the symlink in the sites-enabled directory and restart the Nginx server.

remove the virtual host symlink in the sites-enabled directory

This allows us to enable and disable virtual hosts without deleting the vhost configuration file.