FreeKB - How to configure virtual hosts in nginx
How to configure virtual hosts in nginx

Home > Search > How-to

Before web servers had virtual hosts, you would have had to had a physical server for each website that you wanted to produce.


Virtual hosts allow you to run multiple sites from a single physical server.


Let's say you want to create two sites, site1 and site2. In the /etc/nginx/nginx.conf file, create two server blocks, one for site1 and another for site 2. Notice has default_site. If there is some problem producing, the default site will be produced.

server {
  listen       80 default_server;
  listen       [::]:80 default_server;
  root         /var/www/site1;

server {
  listen       80;
  listen       [::]:80;
  root         /var/www/site2;


Create the /var/www/site1 and /var/www/site2 directories.

[root@server1 ~]# mkdir /var/www/site1
[root@server1 ~]# mkdir /var/www/site2


Create an index.html file for site1 and site2. Add unique content to each index.html file. For example, one could have Welcome to site1 and the other could have Welcome to site2.

[root@server1 ~]# mkdir /var/www/site1/index.html
[root@server1 ~]# mkdir /var/www/site2/index.html


Restart nginx, and ensure nginx is active and running.

[root@server1 ~]# systemctl start nginx
[root@server1 ~]# systemctl status nginx



Use the ls -Z command to view the SELinux permissions of the files in the /var/www/site1 and /var/www/site2 directories. In this example, the index.html context is var_t. nginx needs the type to be httpd_sys_content_t.

[root@server1 ~]# ls -Z  /var/www/site1
-rwxrwxrwx. root root unconfined_u:object_r:admin_home_t:s0 index.html


Use the restorecon command to update all of the directories and files used by nginx to have httpd_sys_content_t.

[root@server1 ~]# restorecon -Rv  /var/www/site1
[root@server1 ~]# restorecon -Rv  /var/www/site2


Use the ls -Z command again to confirm the context is httpd_sys_content_t.

[root@server1 ~]# ls -Z  /var/www/site1
-rwxrwxrwx. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html


Navigating to will now display Welcome to site1, and will display Welcome to site2.

Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter ddcb2 in the box below so that we can be sure you are a human.