9

User Request: https://www.example.com/test

HTTPS requests --> AWS ELB HTTPS Listener --> Apache HTTP

Apache getting http://www.example.com/test

Apache redirect it to http://www.example.com/test/ due to DirectorySlash is On by default.

User ends up with a HTTP request: http://www.example.com/test/

AWS provides a HEAD to detect origin request protocol: %{HTTP:X-Forwarded-Proto}, but how do I tell Apache mod_dir DirectorySlash to use that Header?

Please advise your solution or workaround in this scenario.

starchx
  • 433
  • 10
  • 23

3 Answers3

6

Since rewrite will kick in before DirectorySlash, here is what ended up with and it works:

# Redirect to HTTPS before Apache mod_dir DirectorySlash redirect to HTTP
RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteCond %{LA-U:REQUEST_FILENAME} -d
RewriteRule ^/(.*[^/])$ https://%{HTTP_HOST}/$1/ [R=301,L,QSA]
starchx
  • 433
  • 10
  • 23
  • RewriteOptions AllowNoSlash is needed with apache 2.4. – Lajos Veres Jul 19 '17 at 14:05
  • What is the second condition? – Maciek Semik Mar 03 '19 at 05:17
  • This doesn't work if you have subdomains – Maciek Semik Mar 03 '19 at 09:38
  • This needs to be placed in your vhost config (I tried ever other possible place first... would be nice to include this info). Contrary to Lajos' and Jeffrey's comments, on Apache 2.4.38 (+ backported debian patches) AllowNoSlash was not needed (though perhaps it's set by default?) and it works fine with subdomains (both www-less and with www, the redirect correctly includes or omits the www subdomain and sets https or http correctly depending on which proto was used in the request). I also have `RewriteEngine On` for other rewrites, you might need to add that if you don't already have it. – Luc Dec 16 '20 at 23:17
2

Try using this rule which will kick in before DirecorySlash kicks in

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [NE,R=301,L]
Sameer Naik
  • 218
  • 2
  • 7
  • 1
    Thanks for pointing me the direction. The problem I had is that, Apache will redirect by adding an ending slash, ignore the X-Forwarded-Proto header set by ELB, which is back to http:// – starchx May 24 '17 at 04:49
0

As explained in the relevant DirectorySlash bug report, another option is to include the scheme in the ServerName as mentioned in https://httpd.apache.org/docs/2.4/mod/core.html#servername

Sometimes, the server runs behind a device that processes SSL, such as a reverse proxy, load balancer or SSL offload appliance. When this is the case, specify the https:// scheme and the port number to which the clients connect in the ServerName directive to make sure that the server generates the correct self-referential URLs.

So, instead of:

<VirtualHost *:80>
    ServerName example.com

switch to:

<VirtualHost *:80>
    ServerName https://example.com

And everything, including DirectorySlash will work as expected.

cherouvim
  • 744
  • 3
  • 18
  • 37