How to configure virtual hosts in nginx

Home > Search > How-to
  by

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 www.site1.com has default_site. If there is some problem producing www.site2.com, the default site will be produced.

server {
  listen       80 default_server;
  listen       [::]:80 default_server;
  server_name  www.site1.com;
  root         /var/www/site1;
  }

server {
  listen       80;
  listen       [::]:80;
  server_name  www.site2.com;
  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

 


SELinux

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 www.site1.com will now display Welcome to site1, and www.site2.com 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 in the box below so that we can be sure you are a human.




Comments