VHosts and Directives, Part 1: Externalize vhost configuration in nginx

How to externalize the vhost configuration to a different directory in Linux / Unix.

If we move to our nginx directory our most important file is going to be nginx.conf file. It is most important because it contains the base configuration for everything in our nginx system, including how what handles the host configuration.

vi /etc/nginx/nginx.conf

1.) Within this file we are going to make the following changes:

In http section

Add

include /etc/nginx/vhost.d/*.conf;

below include /etc/nginx/conf.d/*.conf;

2.) Comment out the server block like this

# server {
# listen 80 default_server;
# listen [::]:80 default_server;
# server_name _;
# root /usr/share/nginx/html;
#
# # Load configuration files for the default server block.
# include /etc/nginx/default.d/*.conf;
#
# location / {
# }
#
# error_page 404 /404.html;
# location = /40x.html {
# }
#
# error_page 500 502 503 504 /50x.html;
# location = /50x.html {
# }
# }

Now

3.) Create a directory name vhost.d in /etc/nginx using “mkdir” command

mkdir vhost.d

cd vhost.d

 

4.) Create a new file name default.conf under vhost.d directory.

vim default.conf

5.) Add server code to default.conf and change root to the directory which you like. In our case we have done it to /var/www/html

server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /var/www/html;

# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;

location / {
}

error_page 404 /404.html;
location = /40x.html {
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}

6.) Now create a directory with “mkdir” command using parted option

mkdir -p /var/www/html

7.) Make sure that you haven’t made any typos or added any invalid entries. for this use following command:

nginx -t

8.) Create a html page in /var/www/html

echo "This is my new location" > /var/www/html/index.html

9.) Restart Service

systemctl restart nginx

Or

service nginx restart

Test it by typing in your browser

localhost

Or

your ipaddress

10.) You can check your IP address with ip addr command:

ip addr

11.) If selinux is in enforcing mode and causes problem, then use these commands

semanage fcontext -a -t httpd_sys_content_t "/var/www/html/(/.*)?"
restorecon -R -v /var/www/html

Video Tutorial

That’s all for now. Have questions, post them in the comments.

Add Comment