Dynamically Update /etc/hosts from NGINX
I wanted to guarantee that requests coming from one of my servers going to a domain they host are routed to localhost. The solution I arrived at was to generate a list of domains hosted under NGINX virtual hosts and dynamically updates /etc/hosts
, so go do this I wrote a bash script. This script can then be called via cron (or other scripts scheduled in cron or otherwise) to concatenate to the actual hosts file.
Setup Configuration
First we need to create a directory to hold the custom configuration files called /etc/hosts.d/
and then we want to make a backup of our existing /etc/hosts
file to use as the base, “main” configuration for our script. The files that will be appended to the main file will be in the hosts.d
directory and end with the extension *.conf
.
# Create a configuration directory for hosts.conf files mkdir -p /etc/hosts.d/ # Copy the default /etc/hosts file to be our "main" conf file cp /etc/hosts /etc/hosts.conf
Create Bash Script
Next create a bash script called /usr/local/bin/hosts
that checks for custom configuration files and conditionally includes them into the /etc/hosts
file. You can schedule this script via cron or call it from other scripts on demand if it’s only necessary to regenerate the file sporadically.
Don’t forget to run chmod +x /usr/local/bin/hosts
to make it executable.
#!/bin/bash # # Create the /etc/hosts file using a base configuration and dynamic conf files ################################################################################## HOSTS="/etc/hosts" MAIN="/etc/hosts.conf" CONF="/etc/hosts.d/*.conf" # Test for *.conf files if ls $CONF 1> /dev/null 2>&1; then # Get main and extra conf files cat $MAIN $CONF> $HOSTS else # Get main conf file only cat $MAIN> $HOSTS fi
Send Nginx Virtual Hosts to 127.0.0.1
Next we can leverage all the work so far to create a script that gets all the domains for virtual hosts on Nginx and puts them into a file that can then be appended to /etc/hosts. We’ll call it /usr/local/bin/nginx_to_hosts
and once again remember to make it executable with chmod +x /usr/local/bin/nginx_to_hosts
#!/bin/bash # # Get virtual hosts from Nginx, create custom hosts entries, regenerate hosts file ################################################################################## # This is where we will save the custom hosts entries CONF="/etc/hosts.d/nginx_hosts.conf" # Get a list of all the Nginx virtual host domains domains=`find /etc/nginx/ -type f -name "*.conf" -print0 | xargs -0 egrep '^(\s|\t)*server_name' | sed -r 's/(.*server_name\s*|;)//g'` # Set each domain to point to localhost hosts=$(for domain in $domains; do printf "\n127.0.0.1 $domain"; done) # Create the custom host file for Nginx domains printf "#Nginx Virtual Host Domains $hosts\n" > $CONF # Regenerate /etc/hosts file /usr/local/bin/hosts