Redirect to a 3rd party website


I need to redirect to some 3rd party websites. The issue is that some of the urls works to redirect and some doesn’t work, using redirect_to url

Example 1:

With this URL I just do: redirect_to url

Example 2:

When using: redirect_to url

I get “ERROR URI::InvalidURIError: bad URI(is not URI?)”

So, I tried to just do:

redirect_to URI.encode(url)

… and it works! But then the URL in example 1 is not working anymore. Says the site is not found. No error in Rails though.

So, I need an approach that works with both (all?) URIs. Any ideas?

Write a utility method, e.g. redirect_to sanity_checked(url) that either
returns the original URL if it's good or an encoded version if not.

Which is not to say that simply encoding it will fix every error, so it's
probably worth checking that result too :slight_smile:


Thank you for your time.

How can I check if the URL is “good” or needs to be encoded?

Best Regards


I mean, URI.parse(uri) doesn’t return any error on either of the URIs it seems.

Actually, I think I found a solution now.

I first parse it, like:

uri = URI.parse(the_url)

and then:

redirect_to uri.to_s

Works :slight_smile:

My bad, it does NOT work!

Without looking at the code, it's hard to imagine you're getting the
"ERROR URI::InvalidURIError: bad URI(is not URI?)" exception you
originally reported from other than URI.parse, but -- can you get a
stack trace to show exactly what's raising that?