Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the final URL after redirects using Ruby?

If http://foo.com redirects to 1.2.3.4 which then redirects to http://finalurl.com, how can I use Ruby to find out the landing URL "http://finalurl.com"?

like image 347
Mark Avatar asked Feb 01 '11 20:02

Mark


2 Answers

Here's two ways, using both HTTPClient and Open-URI:

require 'httpclient'
require 'open-uri'

URL = 'http://www.example.org'

httpc = HTTPClient.new
resp = httpc.get(URL)
puts resp.header['Location']
>> http://www.iana.org/domains/example/

open(URL) do |resp|
  puts resp.base_uri.to_s
end
>> http://www.iana.org/domains/example/
like image 174
the Tin Man Avatar answered Nov 16 '22 22:11

the Tin Man


Another way, using Curb:

def get_redirected_url(your_url)
  result = Curl::Easy.perform(your_url) do |curl|
    curl.follow_location = true
  end
  result.last_effective_url
end 
like image 44
fsabattier Avatar answered Nov 16 '22 21:11

fsabattier