0

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?

Mbrouwer88
  • 163
  • 1
  • 3
  • 11

2 Answers2

3

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.

Gerald Schneider
  • 23,274
  • 8
  • 57
  • 89
  • Typo: "not" -> "note"? Also, shouldn't such a redirect be a 301 (permanent) - although if HSTS is enabled, maybe that doesn't really matter? – MrWhite Mar 08 '17 at 16:03
  • Of course, for both issues. I changed the answer to reflect this. The response type doesn't really matter for the user, but it does for search engines. – Gerald Schneider Mar 08 '17 at 16:12
1

The recommended way is to use Redirect option inside the virtual host as explained here. Here is a config snippet:

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName www.example.com
   Redirect permanent / https://secure.example.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName secure.example.com
   DocumentRoot /usr/local/apache2/htdocs
   SSLEngine On
# etc...
</VirtualHost>

This will redirect all requests to http://www.example.com to https://secure.example.com.

Khaled
  • 36,533
  • 8
  • 72
  • 99
  • But that does only redirect request to a specific url, and not if someone visits http://domain.tld/somethingelse – Orphans Mar 08 '17 at 14:51
  • @Orphans actually it does. From [the documentation](http://httpd.apache.org/docs/current/mod/mod_alias.html#redirect): `any request beginning with URL-path will return a redirect request to the client at the location of the target URL. Additional path information beyond the matched URL-path will be appended to the target URL` – Gerald Schneider Mar 08 '17 at 15:06