Hello!
We threw together a quick & simple script to dynamically update your .htaccess files within apache to add your dynamic IP address to the allow / deny fields.
If you’re looking to password protect an admin area (for example) but your office only has a dynamic IP address, then this script might be handy for you.
Its an extremely simple script that polls your dynamic hostname (if you use no-ip.org or dyndns.org for example) every 15 minutes as a cron job and, if it has changed, updates the .htaccess file
Hopefully it will make your life just a little bit easier
Sample Cron entry :
*/15 * * * * /bin/sh /usr/local/bin/htaccessdynamic.sh yourhostname.dyndns.org /var/www/website.com/public_html/.htaccess > /dev/null 2>&1
And now the script :
#!/bin/bash
# Dynamic IP .htaccess file generator
# Written by Star Dot Hosting
# www.stardothosting.com
dynDomain="$1"
htaccessLoc="$2"
dynIP=$(/usr/bin/dig +short $dynDomain)
echo "dynip: $dynIP"
# verify dynIP resembles an IP
if ! echo -n $dynIP | grep -Eq "[0-9.]+"; then
exit 1
fi
# if dynIP has changed
if ! cat $htaccessLoc | /bin/grep -q "$dynIP"; then
# grab the old IP
oldIP=`cat /usr/local/bin/htold-ip.txt`
# output .htaccess file
echo "order deny,allow" > $htaccessLoc 2>&1
echo "allow from $dynIP" >> $htaccessLoc 2>&1
echo "allow from x.x.x.x" >> $htaccessLoc 2>&1
echo "deny from all" >> $htaccessLoc 2>&1
# save the new ip to remove next time it changes, overwriting previous old IP
echo $dynIP > /usr/local/bin/htold-ip.txt
fi
# Dynamic IP .htaccess file generator
# Written by Star Dot Hosting
# www.stardothosting.com
dynDomain="$1"
htaccessLoc="$2"
dynIP=$(/usr/bin/dig +short $dynDomain)
echo "dynip: $dynIP"
# verify dynIP resembles an IP
if ! echo -n $dynIP | grep -Eq "[0-9.]+"; then
exit 1
fi
# if dynIP has changed
if ! cat $htaccessLoc | /bin/grep -q "$dynIP"; then
# grab the old IP
oldIP=`cat /usr/local/bin/htold-ip.txt`
# output .htaccess file
echo "order deny,allow" > $htaccessLoc 2>&1
echo "allow from $dynIP" >> $htaccessLoc 2>&1
echo "allow from x.x.x.x" >> $htaccessLoc 2>&1
echo "deny from all" >> $htaccessLoc 2>&1
# save the new ip to remove next time it changes, overwriting previous old IP
echo $dynIP > /usr/local/bin/htold-ip.txt
fi

Thanks!
Very useful! thanks for this!
This saved a few headaches – thanks
What CHMOD permission must the htaccess file be for this script to work?
Whatever the user running the script in order to write to the file