Shell Script to send HTTP Code 301 Moved Permanently Followed by Actual URL Redirection

in Categories File-management last updated April 10, 2008

This script depends upon shell array.

#!/bin/bash
# Shell script to update old php files to point out to new CMS url
# it placed http code 301.
# You must create an array in following format:
# path/to/old/url1.php  path/to/new/url/slug/
# --------------------------------------------------------------------------
# Copyright (C) 2008 nixCraft project <http://www.cyberciti.biz/tips/contact-us>
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
declare -a t=("http://domain.com/1.php" "http://domain.com/new/path/slug/"
"http://domain.com/2.php" "http://domain.com/new/path/slug/"
"http://domain.com/3.php" "http://domain.com/new/path/slug/"
"http://domain.com/4.php" "http://domain.com/new/path/slug/"
"http://domain.com/5.php" "http://domain.com/new/path/slug/")
# set array total array size -1 ; if you have 5 item it should set to 4
for i in `seq 0 4` 
do
	#only work on zero or even element  
	if [ $i -eq 0 -o  $( expr $i % 2 ) -eq 0  ]; then
		s="${t[$i]}"
                d="${t[` expr $i + 1 ` ]}"
                file=$(basename $s)
 		echo "Patching $file...."
		if [ -f $file ]; then
		# if file exists, create new php redirection code
			echo '<?php'>$file
			echo 'header("HTTP/1.1 301 Moved Permanently");'>>$file
			echo 'header("Location: ' $d '");'>>$file
			echo '?>'>>$file
		fi
	fi
done

Share this on: