How to setup virtual host on Ubuntu 14.04 and Nginx

NGINX, Ruby on Rails, Ubuntu, Web Development, 2015-06-17 00:15:11 UTC

First before we start this tutorial, you must have a Nginx web server on your Ubuntu 14.04.

1. If Nginx already installed, there is a default file configuration for sites in /etc/nginx/sites-available/default. Copy and rename it as a starting point;

$ sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/mydomain.com



2. Open the file and fit into something like this;

server {
        listen   80; ## listen for ipv4; this line is default and implied
        #listen   [::]:80 default ipv6only=on; ## listen for ipv6

        root /var/www/mydomain.com/public_html;
        index index.html index.htm;

        # Make site accessible from http://localhost/
        server_name *.mydomain.com;
}



3. Create a symlink

$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com



4. Delete /etc/nginx/sites-enabled/default configuration to avoid the "conflict server name error"


5. Restart Nginx

$ sudo service nginx restart



If you want to add another virtual host, in an example is a subdomain, you can follow above steps but at point 2, you should comment a line contains "listen to port 80".

The configuration is something like below;

server {
        #THIS EXAMPLE INCLUDE RAILS CONFIG ENVIRONMENT AND PASSENGER        
   
        #listen   80; ## listen for ipv4; this line is default and implied
        #listen   [::]:80 default ipv6only=on; ## listen for ipv6

        root /var/www/subdomain.mydomain.com/public;


        # Make site accessible from http://localhost/
        server_name subdomain.mydomain.com;
         
        #rails configuration
        passenger_enable on;
        passenger_app_env development;
        
}







Share: