pinguinone
pinguinone

Reputation: 473

.HTAccess multiple redirect

I want to achieve that if a user write:

http://www.example.com/url/index.html
http://www.example.com/url/
https://example.com/url/index.html
https://example.com/url/

will be always redirect to:

https://www.example.com/url/

So I write this redirect istruction in .htaccess (I'm not an expert of this so I think it could be here the problem) and it seems to work:

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

The problem is that from some SEO tools it seems that it make the work in more than 1 redirection. Infact I think that if the user look for:

http://example.com/url/

it redirects to

https://example.com/url/

after to

https://www.example.com/url/

How can I change the previuos code to make it better and make everything with 1 redirection?

Thanks

Upvotes: 1

Views: 2356

Answers (1)

Amit Verma
Amit Verma

Reputation: 41249

You can shorten your http to https redirect rules. Instead of using two separate rules for http and htttps://www you can just use a single rewrite rule that will handle both in one redirection .

RewriteEngine on
# http to https and non-www to www
RewriteCond %{ENV:HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^.*$ https://www.%1%{REQUEST_URI} [NE,R=301,L]
# remove index.html
RewriteRule ^(.*)\.index\.html$ /$1 [L,R=301]

Clear your browser cache before testing this htaccess.

Upvotes: 2

Related Questions