htaccess and Dynamic IP Addresses

0
(0)

How to apache htaccess Allow from Dynamic IP Address

Apache web server access control via htaccess, to allow authorized access to web pages.

The Apache directive Allow from make it possible to exclude a specific IP from the login prompt. Unfortunately, it is not possible to pass host names and FQDN. The following script reads the Dynamic IP of a hostname and add them into the file htaccess.

The following shell script resolve the IP address and write them into the htaccess file. Insert the following lines out from console with copy & paste, so that the script file is created.

cat << EOF > ./allow_myhost.sh
#!/bin/sh
htpath="/var/www/blog/"
grep -lr "#DDNS" $htpath | while read i; do
sed -i '/#DDNS-IP$/d' $i
grep -i "#DDNS$" $i | while read j; do
words=( $j )
ddns="${words[2]}"
ip="$(host $ddns)"
if [ "$ip" == "${ip%% has address *}" ]; then
continue;
fi
ip="${ip##* has address }"
sed -i 's/^\('"$j"'\)$/\1\nAllow from '"$ip"' #DDNS-IP/' $i
done
done
EOF

Copy Paste

The script here on a CentOS host rewrites the htaccess file. The line Allow from with the tag #DDNS reads the host name, and the host’s resolved IP is written on the next line with the tag #DDNS-IP. The path variable htpath can be DocumentRoot or a subdirectory, whereby the script edits all occurring .htaccess files recursively from htpath.

The file htaccess is stored in the web directory to be protected. Using cd to change to the desired directory and insert the following lines will copy & paste out from the console, this generates the file .htaccess.

cat << EOF > .htaccess
AuthName "A Blog"
AuthType Basic
AuthUserFile /home/jonny/.htpasswd
AuthGroupFile /dev/null
Order deny,allow
Deny from all
require valid-user
Allow from myhome.dyndns.org #DDNS
Allow from 123.123.123.123 #DDNS-IP
Satisfy Any
EOF

Copy Paste

The lines with #DDNS and #DDNS-IP (#) use to tagging.

The script has yet to be made executable.

chmod 755 allow_myhost.sh

Keep the dynamic IP resolution up to date with crontab -e to create a cron job.

*/5 * * root /home/jonny/allow_myhome.sh >/dev/null 2>&1

Older Linux need to restart the cron daemon to the cron job come active.

service crond restart

Note. Apache 2.4 directive Require
Apache 2.x directive Allow from

Apache 2.x mod_access_compat

Order deny,allow
Deny from all

Apache 2.4 mod_authz_host

Require all denied

The directives Allow Deny provided by mod_access_compat are deprecated and will no longer be supported in the future release. It is recommended to use the new directives.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *