Adam Hill
Adam Hill

Reputation: 375

301 redirect for index.html and all http,https, www and non-www version of homepage URL to https://www root url via htaccess

I want to 301 redirect the following URL’s via htaccess file

Which means I need to force SSL(https) version and force the www across the whole website.

In addition I also want to 301 redirect the index.html to the https and www version of the homepage url.

I want to 301 redirect the following urls:

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

To

“https://www.example.com”

In addition to that I need all urls of the site to be redirected to https://www version like this:

“https://www.example.com/new-site.html”

Heres what I am using right now:

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

RewriteCond %{HTTP_USER_AGENT} libwww-perl.* 
RewriteRule .* ? [F,L]
RewriteBase /
RewriteRule ^index\.html$ / [NC,R,L]

But the above rules seem to give me a 301--->302-----200 ok redirect for 2 url's with /index.html and 301 for the rest.

It gives a 302 from:

“https://www.example.com/index.html”

To this

“https://www.example.com/“

Thank you.

Upvotes: 2

Views: 645

Answers (2)

anubhava
anubhava

Reputation: 785266

You can do all this in a single rule:

RewriteEngine On

## add www and turn on https in same rule
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{REQUEST_URI} /index\.html$ [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule (?:^|(.+)/)(?:index\.html)?$ https://www.%1/$1 [R=301,L,NE]

Upvotes: 1

Adam Hill
Adam Hill

Reputation: 375

Ok so I figured it out myself:

Here's how it will work, just needed to add R=301 in the last rule and not just R

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

RewriteCond %{HTTP_USER_AGENT} libwww-perl.* 
RewriteRule .* ? [F,L]
RewriteBase /
RewriteRule ^index\.html$ / [NC,R=301,L]

Upvotes: 0

Related Questions