June 7, 2012

Beginner

How To Set Up nginx Virtual Hosts (Server Blocks) on CentOS 6

Tagged In: Nginx, Cent Os

About Virtual Hosts


Virtual Hosts are used to run more than one website or domain off of a single virtual private server.

Note: according to the nginx website, Virtual Hosts are called Server Blocks on nginx. However, for the sake of easy comparison with Apache, I'll refer to them as virtual hosts throughout this tutorial.

Intro


Make sure that nginx is installed on your VPS. If it is not, you can quickly install it with 2 steps.
Install the EPEL repository:
 su -c 'rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm'

Install nginx
yum install nginx

Step One— Create a New Directory


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, the command automatically generates all the parents for the new directory.
sudo mkdir -p /var/www/example.com/public_html

You will need to designate an actual DNS approved domain, or an IP address, to test that a virtual host is working. In this tutorial we will use example.com as a placeholder for a correct domain name.

However, should you want to use an unapproved domain name to test the process you will find information on how to make it work on your local computer in Step Six.

Step Two—Grant Permissions


We need to grant ownership of the directory to the right user, instead of just keeping it on the root system. You can replace the "www" below with the appropriate username.
sudo chown -R www:www /var/www/example.com/public_html

Additionally, it is important to make sure that everyone is able to read our new files.
sudo chmod 755 /var/www

Now you are all done with permissions.

Step Three— Create the Page


We need to create a new file called index.html within the directory we made earlier.
sudo vi /var/www/example.com/public_html/index.html

We can add some text to the file so we will have something to look at when the the site redirects to the virtual host.
<html>
  <head>
    <title>www.example.com</title>
  </head>
  <body>
    <h1>Success: You Have Set Up a Virtual Host</h1>
  </body>
</html>

Save and Exit

Step Four—Set Up the Virtual Host


The next step is to enter into the nginx configuration file itself.

sudo vi /etc/nginx/conf.d/virtual.conf

The virtual host file is already almost completely set up on your virtual server. To finish up, simply match the following configuration, modifying the server name and file location as needed:
#
# A virtual host using mix of IP-, name-, and port-based configuration
#

server {
    listen       80;
#    listen       *:80;
    server_name  example.com;

    location / {
        root   /var/www/example.com/public_html/;
         index  index.html index.htm;
    }
}

Save and exit.

Step Five—Restart nginx


We’ve made a lot of the changes to the configuration. Restart nginx and make the changes visible.
/etc/init.d/nginx restart

Optional Step Six—Setting Up the Local Hosts


If you have been using an actual domain or IP address to test your virtual servers, you do not need to set up local hosts. However, if you are using a generic domain that you do not own, this will guarantee that, on your computer only, you will be able to customize it.

For this step, make sure you are on the computer itself, not your VPS.

To proceed with this step you need to know your computer’s administrative password, otherwise you will be required to use an actual domain name or your IP address to test the virtual hosts.

Assuming that you do have admin access (gained by typing su and entering the correct password) here is how you can set up the local hosts.

On your local computer, type:
nano /etc/hosts

You can add the local hosts' details to this file, as seen in the example below. As long as line with the IP address and server name is there, directing your browser toward, say, example.com will give you all the virtual host details for the corresponding IP address that you designated.
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost

#Virtual Hosts 
12.34.56.789    www.example.com 

However, it may be a good idea to delete these made up addresses out of the local hosts folder when you are done to avoid any future confusion.

Step Seven—See Your Virtual Host in Action


Once you have finished setting up your virtual host, you can see how it looks online. Point your browser to your domain name or IP address, and you should see that the page displays, "Success—You Have Set Up a Virtual Host"

Adding More Virtual Hosts


To create additional virtual hosts, you can just repeat the process above, being careful to set up a new document root with the appropriate new domain name each time. Then just copy and paste the new Virtual Host information into the nginx Config file, as shown below
#
# A virtual host using mix of IP-, name-, and port-based configuration
#

server {
    listen       80;
#    listen       *:80;
    server_name  example.com;

    location / {
        root   /var/www/example.com/public_html/;
         index  index.html index.htm;
    }
}


server {
    listen       80;
#    listen       *:80;
    server_name  example.org;

    location / {
        root   /var/www/example.org/public_html/;
         index  index.html index.htm;
    }
}




By Etel Sverdlov

Share this Tutorial

Vote on Hacker News

Try this tutorial on an SSD cloud server.

Includes 512MB RAM, 20GB SSD Disk, and 1TB Transfer for $5/mo! Learn more

Create an account or login:

33 Comments

Write Tutorial
  • Gravatar digitalocean over 1 year

    I've just finished setting up a droplet using your: https://www.digitalocean.com/community/articles/how-to-install-linux-nginx-mysql-php-lemp-stack-on-centos-6 (which I copy/pasted my way through without issue). I have just ran through this guide too on setting up a virtual host. When I tried to access a .php file though, the browser tried to download the content. I assumed the .php config in the /etc/nginx/conf.d/default.conf would have handled it. Instead for my virtual host I am using: server { listen 80; server_name www.example.com example.com; root /var/www/example.com/public_html/; index index.php index.html index.htm; try_files $uri /index.php; location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } The try_files is to push all non-file requests - example.com/some/path/some/var - to the index.php file for typical MVC framework.

  • Gravatar Moisey over 1 year

    If the browser tried to download the PHP file that means that you do not have an interpreter running. Please make sure that you ran: # sudo service php-fpm restart Or as root: # service php-fpm restart This will then run php-fpm which is what nginx will proxy to, to process php scripts.

  • Gravatar sario120 12 months

    I tried these configurations, very nice and working all these up to 6th step. but when i tried for virtual hosting, it doesn't working, I gave them entry in /etc/hosts as ip nginx.com and I changed thier root directories... Why is this no working? Please help

  • Gravatar M. Farid lutfi 12 months

    i've try the virtual hosts server blocks and it's success. but when i try to adding more website/multiple site on the virtual.conf, i only get succes for the first site. other site cannot rearch server. i have dig the website and it's success only for the first site. below is my virtual.conf # # A virtual host using mix of IP-, name-, and port-based configuration # server { listen 80; # listen *:80; server_name mfaridlutfi.com; location / { root /var/www/mfaridlutfi.com/public_html/; index index.php index.html index.htm; try_files $uri $uri/ /index.php?q=$uri&$args; } error_page 404 /404.html; location = /404.html { root /var/www/mfaridlutfi.com/public_html/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /var/www/mfaridlutfi.com/public_html/; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 location ~ \.php$ { root /var/www/mfaridlutfi.com/public_html/; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location ~ /\.ht { deny all; } } server { listen 80; # listen *:80; server_name designev.com; location / { root /var/www/designev.com/public_html/; index index.php index.html index.htm; try_files $uri $uri/ /index.php?q=$uri&$args; } } server { listen 80; # listen *:80; server_name smartphonereviewers.com; location / { root /var/www/smartphonereviewers.com/public_html/; index index.php index.html index.htm; try_files $uri $uri/ /index.php?q=$uri&$args; } } the mfaridlutfi.com is success loading, the designev.com and smartphonereviewers cannot reach the server. any help ? thanks

  • Gravatar Kamal Nasser 12 months

    @M. Farid lutfi: The websites are loading fine for me. It could be DNS propagation that took a long time.

  • Gravatar droidlabour 9 months

    In case of virtual hosting, the server_name directive must contain both example.com and www.example.com if any of them are omitted then nginx will redirect the missing url request to the default server_name. Example: server { .................... .................... server_name defaultwebsite.com ..................... ..................... } server { .................... .................... server_name example.com; .................... .................... } In this case if you request for www.example.com then nginx will redirect you to the default server name ie defaultwebsite.com It doesn't matter even if you setup the CNAME record for www.example.com to example.com The correct form must be server_name example.com www.example.com

  • Gravatar rogerpack2005 9 months

    yes suggest you update this to have server_name also include www...

  • Gravatar Harsh Baid 8 months

    This tutorial is currently not working! I tried this and when i go on to my website. It just downloads the index.php file? Any help???

  • Gravatar Kamal Nasser 8 months

    @Harsh: This article doesn't configure nginx to work with php. Do you have php-fpm installed? Install it if you do not and add this block to your nginx virtualhost config: https://p.kk7.me/rowumehile.nginx

  • Gravatar romel.verterra 6 months

    Same problem here, I do everything in this tutorial on the droplet I created but it just do the download instead of processing php file. I try service php-fpm restart and it is reports okay but still no success.

  • Gravatar Kamal Nasser 6 months

    @romel.verterra: See my comment above.

  • Gravatar i3ringit 6 months

    This worked great. Thanks for the article.

  • Gravatar felipe.ita 6 months

    I'm having a problem with multiple domains. I'm hosting two magento sites on same server but only the first is working. This is my virtual.conf: server { listen 80; server_name www.coopmed.com.br *.coopmed.com.br; location / { root /usr/share/nginx/html; index index.html index.php; ## Allow a static html file to be shown first try_files $uri $uri/ @handler; ## If missing pass the URI to Magento's front handler expires 30d; ## Assume all files are cachable rewrite ^/index.php\?action=(.*)$ /$1 last; } server { listen 80; server_name www.comercill.com.br *.comercill.com.br; location / { root /usr/share/nginx/html2; index index.php index.html; ## Allow a static html file to be shown first try_files $uri $uri/ @handler; ## If missing pass the URI to Magento's front handler expires 30d; ## Assume all files are cachable rewrite ^/index.php\?action=(.*)$ /$1 last; } I've tryed lots of configurations but none worked. If I change the root for both (ex: root /usr/share/nginx/html/coopmed and root /usr/share/nginx/html/comercill) don't work (sorry for any mistakes, english isn't my native language)

  • Gravatar Kamal Nasser 6 months

    @felipe.ita: Have you restarted nginx?

    sudo service nginx restart

  • Gravatar felipe.ita 6 months

    Yes, I did. But still don't work.

  • Gravatar Kamal Nasser 6 months

    @felipe.ita: Have you figured it out? If not, please create a community question.

  • Gravatar josephcapers 5 months

    I followed each step of the diaspora install and I went to my domain and it only showed "It Works" page. So I tried to use this manual to set up a virtual host, now I am getting this error my homepage: 403 Forbidden nginx/1.0.15

  • Gravatar Kamal Nasser 5 months

    @josephcapers: Please do not duplicate your questions. (https://www.digitalocean.com/community/articles/how-to-install-diaspora-on-a-centos-6-x86-vps) Please create a community question: https://www.digitalocean.com/community/questions/new

  • Gravatar witdodo 3 months

    missing step : you need to add user before this step : sudo chown -R www:www /var/www/example.com/public_html =============== useraddd username ================ (to replace www:www)

  • Gravatar chrismckay.me 3 months

    @Kamal I'm trying to set up subdomains but no luck. I went ahead and created a CNAME record for test.example.com and it maps to @. I created two server blocks with this config - http://pastebin.com/JtWc3cK6. What am I missing? Thanks

  • Gravatar Kamal Nasser 3 months

    @chrismckay.me: Replace it with https://p.kk7.me/puvakiwufu.nginx, restart nginx. Does that fix it?

  • Gravatar techspecx 2 months

    Worked perfectly thank you.

  • Gravatar techspecx 2 months

    Also server naming conventions are below and theymay be defined using exact names, wildcard names, or regular expressions: server { listen 80; server_name example.org www.example.org; ... } server { listen 80; server_name *.example.org; ... } server { listen 80; server_name mail.*; ... } server { listen 80; server_name ~^(?.+)\.example\.net$; ... } Hope this helps.

  • Gravatar l33.adrian about 1 month

    Wow thanks for the guide. I followed everything and managed to make it work. just a small question. what is the difference of setting up virtual host on non Centos? i noticed other linux distro like Ubuntu needs to create some softlink and directory like /etc/nginx/sites-available/default and /etc/nginx/sites-available/example.com ? here's the link for the Ubuntu version of setting up of virtual host https://www.digitalocean.com/community/articles/how-to-set-up-nginx-virtual-hosts-server-blocks-on-ubuntu-12-04-lts--3

  • Gravatar Kamal Nasser about 1 month

    @l33.adrian: The config is the same, the only difference is where to store the files :]

  • Gravatar yazirarafath about 1 month

    When I reloaded nginx after editing Virtual Hosts I got the following error. I was having [root@*********** conf.d]# service nginx reload nginx: [warn] conflicting server name "**********" on 0.0.0.0:80, ignored Reloading nginx: [ OK ] Then I changed the entry as follows. That fixed it! :) server { listen MYSERVERIP:80; # listen *:80; server_name MYDOMAIN.TLD; location / { root /var/www/MYDOMAIN.TLD/public_html/; index index.html index.htm; } } Thank you very much for this useful tutorial.

  • Gravatar yazirarafath about 1 month

    Error : [root@indianrockers conf.d]# /etc/init.d/nginx restart nginx: [emerg] "location" directive is not allowed here in /etc/nginx/conf.d/vir tual.conf:18 nginx: configuration file /etc/nginx/nginx.conf test failed Virtual Conf File : http://pastebin.com/ugEnvj8q Default Conf File : http://pastebin.com/XWpZrxGK Any earliest help would be appreciated.

  • Gravatar Kamal Nasser about 1 month

    @yazirarafath: The location block should be inside the server block, move line 14 to the bottom of the file.

  • Gravatar yazirarafath about 1 month

    @Kamal Nasser : Is this correct? http://pastebin.com/WVSPBFAR Another doubt : What am I to do with default.conf? Shall I delete it?

  • Gravatar Kamal Nasser about 1 month

    @yazirarafath: Yes, that looks fine. You can leave the default.conf file there, it shouldn't affect other sites.

  • Gravatar yazirarafath about 1 month

    @Kamal Nasser : I have already hosted a website as per https://digitalocean.com/community/articles/how-to-install-linux-nginx-mysql-php-lemp-stack-on-centos-6. Now do I need to move the settings of that site from default.conf to virtual.conf or shall I just let the site run as it is and configure the other sites in the virtual host?

  • Gravatar Kamal Nasser about 1 month

    @yazirarafath: It doesn't matter -- you can store it wherever you want. You should probably move it to another file just so it's clear where every site's settings are stored.

  • Gravatar Jimmy Rittenborg 4 days

    If I want to install a CMS for these virtual hosts, although these clients is never going to have directly access to to server itself (through ssh or ftp/sftp) only through a file archive in the CMS, would it then still be considered more secure and a best practice to create a new user for each of these virtual hosts? Would that make it easier to keep an eye on disk usage for each of these in the future? or just complicate stuff as I'm not trying to reinvent PLESK.

Leave a Comment

Create an account or login:
Ajax-loader