Search code examples
apache.htaccesshttp-redirectmod-rewrite

.htaccess - "Too many redirects" when trying to force https


I am trying to force a subfolder (/bbb/) of my root domain to show always as https. Also my .htaccess file take care of the extensions of the pages.

I have put the .htaccess file inside my /bbb/ folder but I get "Too many redirects" when I try to force to connect to https, without it everything works fine.

Whats wrong in my code?

Options +FollowSymLinks -MultiViews
Options +Indexes
AcceptPathInfo Off
RewriteEngine on
RewriteBase   /

ErrorDocument 404 https://example.co.uk/404page/404.html

#Force from http to https
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{HTTP_HOST} !^bbb.example.co.uk/$
RewriteRule ^(.*)$ https://bbb.example.co.uk/$1 [R=301]

#take off index.html
 RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC]
RewriteRule . http://www.%{HTTP_HOST}%1 [R=301,NE,L]

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]    

## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [L]

Solution

  • Problem is in this rule:

    #Force from http to https
    RewriteCond %{SERVER_PORT} 80 
    RewriteCond %{HTTP_HOST} !^bbb.example.co.uk/$
    RewriteRule ^(.*)$ https://bbb.example.co.uk/$1 [R=301]
    

    Change this rule to:

    #Force from http to https
    RewriteCond %{HTTPS} !on 
    RewriteCond %{HTTP_HOST} =bbb.example.co.uk
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L,NE]
    

    You have condition reversed due to use of ! at start and have an extra slash at end which will never be matched hence making your condition always return true.

    Make sure to clear your browser cache before testing this.