Search code examples
apachemod-rewriteamazon-cloudfront

How to prevent Apache mod_rewrite from redirecting to http if I don't include the absolute path?


I have several RewriteRule for 301 redirects in my VirtualHost config. If I don't include the absolute path in the substitution path, Apache will redirect to http protocol instead of https, even if the original url is https. This will result in an additional redirect when inspecting the network in the browser.

So, if I include the full path, it will work as expected and will redirect https://www.example.com/en/mobile/something to https://www.example.com/en/something:

RewriteRule ^/?en/mobile/(.*)$ https://www.example.com/en/$1 [R=301,L]

But if I don't include the full path, it will redirect to redirect to http first (which is handled by AWS CloudFront):

RewriteRule ^/?en/mobile/(.*)$ /en/$1 [R=301,L]

Is it possible to preserve the protocol if I don't include the absolute path in the code? I have updated my website recently and several url paths were changed. I just want to keep the code cleaner and don't repeat the full url in every rule.


Solution

  • This is most probably caused by being behind AWS Cloudfront which is probably using plain http to communicate with your Apache/application server.

    By default, Apache generates self-referential URLs (scheme + hostname + port) based on the request. To override this, you would need to set the scheme (ie. https) in the ServerName directive in the VirtualHost config. For example:

    ServerName https://www.example.com
    

    From the Apache docs:

    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.

    You may also need (or want) to set UseCanonicalName On.