HTTP to HTTPS rewrite not working the first time

apache-2.2mod-rewriteredirection

I all, I have a strange problem with redirection to HTTPS on Debian running Apache.

  • When a user visits http://subdomain.url.nl for the first time, a page not found is reported.
  • When the user visits https instead, it works.
  • Then user closes the browser, start browser again, and goes to http (without https), the redirect is suddenly working.

I use this rewrite rule. (* hide the IP address in this post)

  <VirtualHost 10.*.*.*:80>
RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
ReWriteRule ^/(.*) https://%{HTTP_POST}/$1 [NC,R,L]
</VirtualHost>

So, only the "first time" a user visits the site via http, the redirect does not work. Any idea how to solve this?

Best Answer

The variable HTTP_POST doesn't exist. You most probably meant HTTP_HOST:

RewriteEngine on
ReWriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]

Since this is a permanent redirect the response code 301 should be returned, the default for [R] is 302 (Moved Temporarily).

Also note that the condition checking for port other than 443 is unnecessary, the VirtualHost only binds to port 80. Requests on port 443 will never reach it.

Regarding the working second requests: Do you have HSTS enabled in your SSL configuration? That would explain why clients go to HTTPS straight away for subsequent requests.

Related Topic