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
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.
I haven't validated this works, but from reading the ActiveResource API and quick google search, maybe you can catch the exception, then try to get the location that the request was redirected to, and then retry the operation using the new location?
rescue ActiveResource::Redirection => ex
unless retried
domain = URI.parse(ex.response['Location']).host
retried = true and retry # retry operation
end
end
精彩评论