[Ruby] Get HTTP redirect URL in Ruby

less than 1 minute read

Overview

  • Get the URL of the HTTP redirect destination in Ruby
  • Operation check environment: Ruby 2.7.1 + macOS Catalina

Source code

Save the following contents with the file name get_redirect.rb.

get_redirect.rb


require'net/http'

# Get command line arguments
src_url = ARGV[0]

# Get redirect URL
redirect_url = Net::HTTP.get_response(URI.parse(src_url))['location']

# Output redirect URL
puts redirect_url if redirect_url

Execution example.

$ ruby get_redirect.rb https://bit.ly/3kmTOkc
https://t.co/yITSBp4ino
$ ruby get_redirect.rb https://t.co/yITSBp4ino
https://qiita.com/niwasawa
$ ruby get_redirect.rb https://qiita.com/niwasawa

Reference materials

Tags:

Updated: