Skip to content

Instantly share code, notes, and snippets.

@insparrow
Created March 10, 2013 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save insparrow/5126593 to your computer and use it in GitHub Desktop.
Save insparrow/5126593 to your computer and use it in GitHub Desktop.
Create validated .htaccess rewrite rules in batch using Bash
#!/bin/sh
# Usage: create_rewrite_rules csv_file url username password
# htaccess login credentials optional
OLDIFS=$IFS
IFS=","
file=$1
path=$2
user=""
pass=""
# Exit if arg2 is not present
if [[ -z "$path" ]]; then
echo $'\e[1;31m''Script requires a URL' $'\e[0m'
exit 0
fi
# If arg3 & arg4 are present, set login credentials
if [[ "$3" && "$4" ]]; then
user="--user=$3"
pass="--password=$4"
fi
# Loop through CSV file
while read col1 col2 col3 col4 col5
do
old=$col1
title=$col2
region=$col3
flag=$col4
new=$col5
# Skip if urls do not meet the minimum required length
if [ "${#old}" -lt 10 ] || [ "${#new}" -lt 15 ]; then
continue
fi
# Clean strings (remove line endings added by excel)
# Check with: echo $old | od -c
old=$(echo $old | tr -d "\r\n")
new=$(echo $new | tr -d "\r\n")
# Remove URL that user has prefixed new path with
new=${new:32}
# Check HTTP response for old and new URLS
old_response=$(wget --spider $user $pass $path$old 2>&1 | grep '200 OK')
new_response=$(wget --spider $user $pass $path$new 2>&1 | grep '200 OK')
# If either response is empty (not "200 OK"), skip row
if [[ -z "$old_response" || -z "$new_response" ]] ; then
continue
fi
# Remove first forward slash from old URL
old=${old:1}
# Print rewrite rule
echo "RewriteRule ^$old(/?.*) $new [R=301,L]"
done < $file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment