How To SetUp Nginx Virtual Hosts on Ubuntu 18.04 & 16.04 LTS
Abstract: sudo echo "Hello World..." > /var/www/xyz.com/httpdocs/index.htmlCreate Virtual Hosts File Now set up virtual host configuration file for you domain x
Virtual Host (Known as Server Blocks in Nginx) is used for hosting multiple websites on the single server. In this tutorial, you will get details about creating Virtual Host (Server Block) in Nginx web server on Ubuntu servers.
We are assuming that you already have Nginx installed on your system but in case you don’t have installed it already, Use the following command to install it.
sudo apt update sudo apt install nginxCreate a Sample Project
Now create a sample project to be configured with Virtual Host. Just create a directory to use as document root and put an index.html with demo content.
sudo mkdir -p /var/www/xyz.com/httpdocs sudo echo "Hello World..." > /var/www/xyz.com/httpdocs/index.html
Now set up proper file permissions, so that Nginx web server can access it. We are assuming that you are running Nginx with its default user www-data.
sudo chown -R www-data:www-data /var/www/xyz.com sudo chmod -R 755 /var/www/xyz.comCreate Virtual Hosts File
Now set up virtual host configuration file for you domain xyz.com. You can simply make a copy of default configuration file and make required changes.
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/xyz.com.conf
Edit new virtual host configuration in your favorite text editor and add the below configuration for HTTP and HTTPS settings. If you are not using HTTPS with your site just comment HTTPS Server Block section.
vim /etc/nginx/sites-available/xyz.com.conf
# HTTP Server Block #------------------------------------ server { listen 80; root /var/www/xyz.com/httpdocs; index index.html index.htm; server_name example.com www.example.com; } # HTTPS Server Block #------------------------------------ server { listen 443; server_name xyz.com www.xyz.com; root /var/www/xyz.com/httpdocs; index index.html index.htm; ssl on; ssl_certificate /etc/nginx/ssl/xyz.com/xyz.pem; ssl_certificate_key /etc/nginx/ssl/xyz.com/xyz.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES"; ssl_prefer_server_ciphers on; }Enable Virtual Hosts
Default Nginx reads configuration files located under /etc/nginx/sites-enabled directory. So simply create a soft link of original virtual host file to this directory.
sudo ln -s /etc/nginx/sites-available/xyz.com.conf /etc/nginx/sites-enabled/xyz.com.conf
After making all the configuration in your website Virtual host, Let’s restart Nginx service using the following command.
sudo service nginx restart
You have all done!