Extract Final URL After Curl Follows Redirect
When working with APIs, web scraping, or automated scripts, you often
need to find the ultimate destination of a URL that goes through one or
more HTTP redirects. This article demonstrates how to configure the
curl command-line tool to follow these redirects and
cleanly output only the final resolved URL, bypassing the response body
entirely.
The Standard Command
To extract the final URL, use the following curl
command:
curl -Ls -o /dev/null -w "%{url_effective}\n" http://bit.ly/3Y9Xp2tHow the Command Works
The command combines several of curl’s built-in options
to silence unnecessary output and extract only the target metadata:
-L(or--location): Forcescurlto redo the request on the new place if the server reports that the requested page has moved to a different location (indicated by a 3XX HTTP status code).-s(or--silent): Silent or quiet mode. It hides the progress meter and any error messages, ensuring your terminal output remains clean.-o /dev/null: Redirects the actual HTML body response of the destination page to/dev/null(essentially discarding it), as you only need the URL itself.-w "%{url_effective}\n"(or--write-out): This is the key option. It tellscurlto write out specific information after a completed transfer. The%{url_effective}variable displays the last used URL, which represents the final destination after all redirects. The\nadds a clean line break to the terminal.
Saving the Output to a Variable in Bash
If you are writing a shell script, you can capture the final URL directly into a variable for further processing:
FINAL_URL=$(curl -Ls -o /dev/null -w "%{url_effective}" http://bit.ly/3Y9Xp2t)
echo "The final destination is: $FINAL_URL"This method is highly efficient because it performs the redirect resolution in a single network pass without downloading the payload of the final page.