Skip to content

Instantly share code, notes, and snippets.

@amansrivastava
Created April 26, 2017 11:25
Show Gist options
  • Save amansrivastava/2238070d2b04577240ec22392b835f6e to your computer and use it in GitHub Desktop.
Save amansrivastava/2238070d2b04577240ec22392b835f6e to your computer and use it in GitHub Desktop.
Validate URL redirections using cURL
#!/bin/bash
(
# The redirects: test URL and expected URL, separated by a
# pipe character
REDIRECTS=(
"http://www.google.com|http://www.google.co.in"
)
# Make string comparisons case insensitive, because Apache
# can cast redirected URLs to lowercase
shopt -s nocasematch
# Test each, errrr, test
for REDIRECT in ${REDIRECTS[@]}; do
# Split the test on the pipe, and get the first portion
# as the test URL
TEST_URL=`echo $REDIRECT |cut -d '|' -f1 `
# Split the test on the pipe, and get the second portion
# as the expected URL resulting from the redirects
EXPECTED_URL=`echo $REDIRECT |cut -d '|' -f2 `
# Check the URL using Curl, returning just the HTTP
# status code and the URL at the end of the redirections,
# separated by a space
RESULT=$(curl -I -s -w "%{http_code} %{redirect_url}\\n" "$TEST_URL" -o /dev/null)
# Split the Curl result by a space, and get the first
# portion as the HTTP Status code
HTTP_CODE=`echo $RESULT |cut -d ' ' -f1 `
# Split the Curl result by a space, and get the second
# portion as the URL at the end of the redirections
URL_EFFECTIVE=`echo $RESULT |cut -d ' ' -f2 `
# Compare the end URL with the expected URL, output
# the result as status code, if
# there's an error, an explanation
if [[ "$URL_EFFECTIVE" == "$EXPECTED_URL" ]]; then
echo "$HTTP_CODE : \"$TEST_URL\" reditected to \"$EXPECTED_URL\" as expected."
else
echo "$HTTP_CODE : \"$TEST_URL\" exptected to reach \"$EXPECTED_URL\", reached to \"$URL_EFFECTIVE\""
fi
done
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment