Setup Nginx Virtual Host on CentOS 6

Assume NGINX MySQL PHP (LEMP) has been success installed on CentOS 6, for tutorial how to install visit here

Create a New Directory for web files
The first step in creating a virtual host is to a create a directory where we will keep the new website’s information. This location will be your Document Root in the Apache virtual configuration file later on. By adding a -p to the line of code that allows us to create a folder with a nested folder inside of it

#mkdir -p /var/www/

Grant Ownership Permissions of directory to user (assumed username ‘user’ has been added)

#chown -R user:nginx /var/www/

Additionally, it is important to make sure that everyone will be able to read our new files.

#chmod 755 /var/www

Create index html page to for test within our configurations directory.

#vi /var/www/
<h1>Success: You Have Set Up a Virtual Host</h1>

Turn on Nginx Virtual Host
To setup nginx virtual host, we will need to open up nginx virtual file located at /etc/nginx/conf.d/virtual.conf and you will need to update it with the following configuration

#vi /etc/nginx/conf.d/virtual.conf
server {
listen 80;
root /var/www/;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
# Logging -- access_log /var/www/; error_log /var/www/; # serve static files directly location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt)$ { access_log off; expires max; } }

Restart nginx and php-fpm service

#service nginx restart

Setting Up the Local Hosts
If you have pointed your domain name to your virtual private server’s IP address you can skip this step. You do not need to set up local hosts. Your virtual hosts should work. However, if want to try out your new virtual hosts without having to connect to an actual domain name, you can set up local hosts on your computer alone.

#vi /etc/hosts
# Host Database
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
## localhost
#Virtual Hosts

Test if nginx virtual host has been working by access this at browser

Enable PHP
To enable PHP please add following line to /etc/nginx/conf.d/virtual.conf

#vi /etc/nginx/conf.d/virtual.conf
    # pass the PHP scripts to FastCGI server listening on
    location ~ \.php$ {
        root           /var/www/;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
        include        fastcgi_params;

Create a php info page and add in the following line:

#vi /var/www/

Then Save and Exit.
Restart nginx and php-fpm service again so that all of the changes take effect:

#service nginx restart
#service php-fpm restart

Test if php working by access this at browser

2 thoughts on “Setup Nginx Virtual Host on CentOS 6”

Leave a Reply

Your email address will not be published. Required fields are marked *