Is there a way to know if a page request came from the same application?

Cristian picture Cristian · Oct 25, 2011 · Viewed 9.3k times · Source

In Rails3, is there a way to check if the page I'm rendering now was requested from the same application, without the use of the hardcoded domain name?

I currently have:

def back_link(car_id = '')
  # Check if search exists
  uri_obj = URI.parse(controller.request.env["HTTP_REFERER"]) if controller.request.env["HTTP_REFERER"].present?
  if uri_obj.present? && ["my_domain.com", "localhost"].include?(uri_obj.host) && uri_obj.query.present? && uri_obj.query.include?('search')
    link_to '◀ '.html_safe + t('back_to_search'), url_for(:back) + (car_id.present? ? '#' + car_id.to_s : ''), :class => 'button grey back'
  end
end

But this doesn't check for the "www." in front of the domain and all other possible situations.

It would also be nice if I could find out the specific controller and action that were used in the previous page (the referrer).

Answer

Matthew Rudy picture Matthew Rudy · Oct 25, 2011

I think you're looking at this the wrong way.

If you look around the web, find a site with a search feature, and follow the link you'll see a param showing what was searched for.

That's a good way to do it.

Doing it by HTTP_REFERER seems a bit fragile, and won't work, for example, from a bookmark, or posted link.

eg.

/cars/12?from_search=sports+cars

then you can just look up the params[:from_search]

If you really need to do it by HTTP_REFERER then you probably dont have to worry about subdomains. Just;

def http_referer_uri
  request.env["HTTP_REFERER"] && URI.parse(request.env["HTTP_REFERER"])
end

def refered_from_our_site?
  if uri = http_referer_uri
    uri.host == request.host
  end
end

def refered_from_a_search?
  if refered_from_our_site?
    http_referer_uri.try(:query)['search']
  end
end