Linus
Linus

Reputation: 2819

Redirect to 3rd party website in rails

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: http://example.com/click?a(9999999)p(9999999)prod(999999)ttid(999)url(http%3A%2F%2Fwww.someothersite.se%2Fd%2FBLah-Fooo%2FBar%2F_%2FA-3z324qaF1z140nu%3FNr%3D234234234)

With this URL I just do: redirect_to url

Example 2: http://click.example.com/c/9999/m/9999/t/a/9999/?url=http://www.someothersite.se/sv/foo/bar/baz-99/foo-bar-baz-9999?tm=999999

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?

Using Ruby 1.9.3 and Rails 3.2.5

Upvotes: 0

Views: 1037

Answers (1)

Linus
Linus

Reputation: 2819

Solved it like this:

uri = URI.parse(the_url)
redirect_to uri.to_s
rescue URI::InvalidURIError => encoding
  redirect_to URI.encode(the_url)

Works for my app so far.

Upvotes: 1

Related Questions