Auto update multiple .htaccess file for auto www redirect (cPanel)

By in bash, cPanel, Server Admin on March 24, 2010

This script takes 1 argument i.e. the location of the file that contains the list of the domains to be updated for www redirect.The domains should be listed in the file delimited by a new line.
file:domains.txt

example.com
example2.com
exampler3.com
example4.com

This script finds the username associated with a domain from /etc/userdomains and the document root from /etc/passwd

cat $FILE | while read DOMAIN; do
 
		USERNAME=$(cat /etc/userdomains | grep $DOMAIN | head -n1 | cut -d: -f2)
 
		DOCROOT=$(cat /etc/passwd | grep $USERNAME | cut -d: -f6)/public_html
 
		FILE=$DOCROOT/.htaccess
 
		updateHtaccess $FILE $DOMAIN
 
	done

The function : updateHtaccess

updateHtaccess()
{
	if [ -w $1 ]; then
		writeHtaccess $1 $2
	else
		touch $1
		writeHtaccess $1 $2
	fi
}

And the function : writeHtaccess

writeHtaccess()
{
        COND=$(echo "$2" | sed 's/\./\\\./g')
 
	echo -e "########################################################" >> $1
	echo -e "#      Script written by : Rajesh Sharma               #" >> $1
	echo -e "#      Website : http://www.rajesharma.com             #" >> $1
	echo -e "#      mailto : broncha.rajesh@gmail.com               #" >> $1
	echo -e "########################################################\n" >> $1
 
	echo -e "Options +FollowSymlinks\n" >> $1
	echo -e "RewriteEngine on\n" >> $1
	echo -e "rewritecond %{http_host} ^"$COND"$\n" >> $1
	echo -e "rewriterule ^(.*)$ http://www."$2"/\$1 [r=301,nc]\n" >> $1
 
	echo -e "#	End of the auto redirect block			#\n" >> $1
	echo -e "########################################################\n" >> $1
 
	echo $(date)$'\t'"Htaccess file written for "$'\t'$2 >> 301redir.log	
 
}

This script will only work if you are running cPanel on your server as cPanel maintains the file /etc/userdomains. Also this assumes that the document root for the site is the public_html of the home directory of the user.

Get the full code from here.

:)

Tags: , , , ,

Leave a Reply