rubyopen-uri

Ruby OpenURI allow redirections from https to http


The Ruby open-uri library blocks redirections from https to http with the error

RuntimeError (redirection forbidden: https://link -> http://link)

Is there any way to modify this behavior to allow these redirects? Of course monkey patching OpenURI.redirectable? seems an obvious option but I'd prefer to avoid this if possible. Are there any other options here? Most existing answers suggest open_uri_redirections but this gem is unmaintained and no longer works.


Solution

  • open_uri_redirections gem does nothing special but monkey patching OpenURI.redirectable? in an ugly stateful way.

    If the security consideration doesn't apply (i.e. you don't send cookies/referer) - just rewrite it.

    def OpenURI.redirectable?(uri1, uri2)
      uri1.scheme.downcase == uri2.scheme.downcase ||
      (/\A(?:https?|ftp)\z/i =~ uri1.scheme && /\A(?:https?|ftp)\z/i =~ uri2.scheme)
    end
    

    The only change for this function was in time of 2.4 allowing http->https, so we can assume this is very stable.

    But indeed, consider more full-featured http-client instead