nginx virtualhost

How to create virtual host in nginx

I think this is different from each distribution.
I tried following

  • Ubuntu 15.10
  • nginx 1.9.3

Virtual host directory structure is almost same as Apache.
The difference is symbolic-link. Apache creates symbolic-link by itself. But,
Umm… what you are talking about?
Let’s explain it.

Create root space

Create root, contents space for virtualhost.
Finally, we put contents under this place

sudo mkdir -p /var/www/kiririn.com/public_html
chmod -R kiririn /var/www/kiririn.com/public_html
chmod 755 /var/www

Prepare index.html

Create test html file under /var/www/kiririn.com/public_html as root file

<html>
<body>
<h3>Hello Kiririn</h3>
</body>
</html>

Copy default configuration and edit for new virtualhost

Nginx default file is template. Copy this file as template for new one.

cp /etc/nginx/sites-available/default /etc/nginx/sites-available/kiririn.com

New file is /etc/nginx/sites-available/kiririn.com This is for new virtual host

/etc/nginx/sites-available/kiririn.com

server {
   root /var/www/kiririn.com/public_html;
   server_name kiririn.com www.kiririn.com;
}

Other parts are same as template. Only adding above 2 lines

※ In Ubuntu, Apache also has this directory structure. site-available and site-enabled.
Actually, site-enabled is final load directory, but this directory has only symbolic-link.
In Apache, create file under site-available, create symbolic-link automatically, but nginx doesn’t.

Restart nginx and check

sudo service nginx restart

To access kiririn.com as localhost we need to edit /etc/hosts

127.0.0.1 kiririn.com

Ref

Unixmen