javascriptapachemod-rewritehttpsreferrer

Javascript `document.referrer` vanishes when using a HTTP->HTTPS Apache redirection


I redirect all my websites from HTTP to HTTPS with:

<VirtualHost *:80>
  ServerName example.com
  RewriteEngine on
  RewriteCond %{HTTPS} !on
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>

<VirtualHost *:443>
  ServerName example.com
  DocumentRoot /www/example.com
  SSLEngine on  
  ...
</VirtualHost>

I notice that, when navigating from a site anothersite.com and

How to prevent document.referrer to vanish when using a HTTP->HTTPS redirection via Apache?

Or should I do the automatic HTTP->HTTPS redirection with another method to keep the referrer?


Solution

  • As stated in this answer, it is up to the browser to send the Referrer back after a redirect. And apparently, it does not.

    However, you can write your rule like this and read the referrer from query if it does not exist in headers.

      RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}?referrer=%{HTTP_REFERER}
    

    Note that a user can always spoof referrer. But this method will make it easier to spoof it. Depending on your use case, this solution may be a security issue for you.

    Correction

    According to this answer the referrer will be empty when user:

    switches from a https URL to a http URL.

    Additional information in HTTP specs.