Question

I currently have this in place to redirect all http traffic to https.

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteRule ^/(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]

The above is working OK.

Now I'm trying to add rewrite condition to force all https://www traffic to https without the www.

Please note that this is an AWS Elastic Beanstalk running Apache behind Elastic Load Balancer

=============================

EDIT:

Working code:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]
Was it helpful?

Solution

Try this rule instead:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]

OTHER TIPS

Actually RewriteCond %{HTTP:X-Forwarded-Proto} ^http$ [OR] would be better because !=https fails the ELB health checking. So the full working answer is:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$ [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]

To also take into account the ELB health check use:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !=https [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker
RewriteCond %{SERVER_NAME} ^(www\.)?(.*)$ [NC]
RewriteRule ^/?(.*)$ https://%2/$1 [L,R=301]

Just for anyone looking for a full copy and paste solution using ElasticBeanstalks config files.

  1. Create file inside .ebextensions/, lets call it 01-https.config.
  2. Add the following:
files:
  "/etc/httpd/conf.d/http-redirect.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      RewriteEngine On
      RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR,NC]
      RewriteCond %{HTTP:X-Forwarded-Proto} !https
      RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker
      RewriteRule (.*) https://example.com%{REQUEST_URI}

This takes into consideration ELB health check and will work for the following examples:

which will be redirected to https://example.com

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top