Ruby on Rails - request.env['HTTP_REFERER'] returns nil
Asked Answered
M

2

7

I am trying to save the http_referer so I can send the user back to that url after he has logged in. Right now I have a before_filter in my controllers that sends them to a log in page if a session has not been created via a redirect_to. However when I check the HTTP_REFERER it is nil (whereas 'REQUEST_URI' does return where Im originally coming from).

Thank you.

Moncrief answered 23/6, 2010 at 19:10 Comment(0)
D
14

HTTP_REFERER is an HTTP header set by the browser in the request containing the the address of the previous web page from which a link to the currently requested page was followed. It will not be set when directly navigating to a page.

REQUEST_URI (also available via request.request_uri())is the Uniform Resource Identifier used to access the Rails controller/action and should always be set.

Throw this debugging code into your view:

<ul>
<% request.env.each do |item| %>
    <li><%= item[0] %> : <%= item[1] %></li>
<% end %>
</ul>

If HTTP_REFERER is not set, make sure you are navigating to that page via a link or redirect and see if it is set then.

There is also a chance your browser is not setting the HTTP_REFERER header. Be sure you do not have an add-on affecting this. You can use a nifty Firefox add-on called Tamper Data to see the headers being sent.

Dory answered 23/6, 2010 at 19:20 Comment(2)
Yeah, it doesn't show, however, the code you gave me shows that the request goes through my internal firewall which is most likely filtering the data that I need.... Thanks for the code!Moncrief
@Naujpr: I have updated my answer to include a link to Tamper Data, which may help you solve the problem. Good luck!Dory
D
6

No matter what solution you come up with, you need to be able to handle the empty referer case, because the client has the choice whether or not to specify it. (It's off when you're in Safari's private browsing and Chrome's incognito mode for example)

In Rails you can use redirect_to :back, which will use the HTTP_REFERER if it is set, or raise an error otherwise.

When using redirect_to :back, if there is no referrer, RedirectBackError will be raised. You may specify some fallback behavior for this case by rescuing RedirectBackError.

Desired answered 23/6, 2010 at 20:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.