Search code examples
ruby-on-railshttphttp-redirecthttpsactiveresource

Rails: ActiveResource and Apache Redirect


I have rails applications, which communicate with each other using ActiveResource. I have setup the VHOSTs to redirect every HTTP request to HTTPS. This is the VHOST for one application:

<VirtualHost *.80>
 <Location />
    Redirect permanent / https://my.app.com/
 </Location>
</VirtualHost>

#http requests will forwarded here by the above Redirect
<VirtualHost *.443>

 ....
</VirtualHost>

This redirects find when I access through browser, but when I send HTTP request through ActiveResource, it returns error: Moved Permanently. I understand that this could happen in above setup but how to cope with this situation and make ActiveResource work even it sends request to HTTP ( should be forwarded to HTTPS)?

Thanks,

Imran


Solution

  • There is no way for Rails to automatically redirect ActiveResource calls, since only GET and HEAD requests may be automatically redirected, according to the HTTP spec.

    Thus, a redirect from the server will cause an ActiveResource::Redirection exception to be raised, and you'll have to handle this exception in your code:

    begin
      # Make some ActiveResource calls
    rescue ActiveResource::Redirection
      # Error handling
    end
    

    You could try to make new HTTPS request in the rescue block (perhaps by updating the site attribute of the ActiveResource model). However, you would need this kind of error handling around all ActiveResource operations, which makes your code harder to read and maintain.

    Thus, my recommendation is that you don't attempt to handle redirects in your code, but instead require all clients connecting to your applications to always use the HTTPS version.