Forum: Ruby on Rails test if an external url is valid before redirecting to it?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
73c04e9ef9ca435c5b19a2e765ae6d20?d=identicon&s=25 Max Williams (max-williams)
on 2009-02-10 17:56
In our site, users can have a url associated with their account to which
they are redirected when their login expires.  This can differ from user
to user, and is prone to being mis-copied, or the sites in question not
being there any more etc.  I'd like to test if the url is valid before
sending the user on to it.

So, i want, in the controller, to do something like this -

if external_url_is_valid?(user.expiry_url)
  redirect_to user.expiry_url
  redirect_to "our_default_expiry_page"

Can anyone tell me a nice, simple and efficient way of doing the
"external_url_is_valid?" bit?
5772c599ccab3081e0fffb1d54f3b6de?d=identicon&s=25 Andrew Timberlake (andrewtimberlake)
on 2009-02-10 18:40
(Received via mailing list)
On Tue, Feb 10, 2009 at 6:56 PM, Max Williams <> wrote:

>  redirect_to user.expiry_url
require 'net/http'
require 'uri'

def external_url_is_valid?(url)
  uri = URI.parse(url)
  response = Net::HTTP.start(, uri.port) {|http|
  response.is_a?(Net::HTTPSuccess) ||

Watch the validity of the url - is not valid also won't work, will

I wouldn't do this at the point of redirection, I would do it at the
of saving the redirection url

Andrew Timberlake

"I have never let my schooling interfere with my education" - Mark Twain
73c04e9ef9ca435c5b19a2e765ae6d20?d=identicon&s=25 Max Williams (max-williams)
on 2009-02-10 18:52
That's perfect, thanks Andrew.

You're probably right about testing the validity at the point of adding
it rather than (or as well as) the redirect.  I think i'll put a remote
test button next to the input field, and maybe call it automatically on
change of the field.

Anyway, thanks again.
This topic is locked and can not be replied to.