Too many redirects with mod_rewrite (at most one redirect?)

Viewed 89

I want there to be at most one redirect using my htaccess file. Is that possible?

my htaccess file:

RewriteEngine On
#remove index/index.html
RewriteRule index\.html|index https://example.com/ [R=301,L]

#redirect to non-wwww and https site
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{THE_REQUEST} ^GET\ /(.+)\.html [NC]
RewriteRule ^ /%1? [R=301,L]

#remove .html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.html [NC,L]

If I enter for example http://example.com/foo.html or http://example.com/index then I have two redirects.

If I enter for example http://example.com/ or https://example.com/foo.html then I have only one redirect.

What I want:

  • I want at most one redirect (see last two examples).
  • If I navigate to the home page, then I always want the index/index.html to be removed
  • All http calls should be redirected to https calls
  • All URL which are called with www, should be called without www
  • If I navigate to the subpage (https://example.com/foo.html), then only the html should be removed respectively the user can call the page without .html (https://example.com/foo).

Is this possible? Currently sometimes two redirections happen.

1 Answers

Could you please try following, based on your shown samples. Please make sure you clear your browser cache before testing URLs.

RewriteEngine ON
##Apply https and remove www together for all requests here.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.*)$ [NC]
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [NE,L]

##Server files with backend .html files.
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.*)$ $1.html [L]

##Deal with home page .html stuff here.
RewriteCond %{REQUEST_URI} ^/?$
RewriteRule ^(.*)$ index/index.html [L]
Related