If someone visits my website like:
example.com
www.example.com
http://example.com
http://www.example.com
https://example.com
https://www.example.com
I want to redirect it to https://www.example.com/index.html
. I tried the code below:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.mywebsite.com/index.html$1 [R=301,L,NE]
The above code worked fine however if visitor type https://www.example.com
it will not redirect to https://www.example.com/index.html
and also if visitor uses Google chrome and type www.example.com
it will also not redirect to https://www.example.com/index.html
.
CodePudding user response:
Try the following instead:
RewriteEngine On
# Redirect "/" to "/index.html" (HTTPS www)
RewriteRule ^$ https://www.example.com/index.html [R=301,L]
# Redirect non-www to www ( HTTPS)
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Redirect HTTP to HTTPS (any remaining URLs)
RewriteCond %{SERVER_PORT} 80
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
Just the first rule satisfies the requirements outlined in your question. All the stated URLs are redirected to https://www.example.com/index.html
(HTTPS www).
The second and third rules are just generic canonical (www HTTPS) redirects for anything else, including if the user requests /index.html
.
Test first with a 302 (temporary) redirect to avoid potential caching issues. You will need to clear your browser cache before testing.
A look at your rules...
RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.example.com/index.html$1 [R=301,L,NE]
Your first rule redirects to HTTP, not HTTPS, which is the intended target.
The second rule redirects everything (including any static assets) to /index.html
and appends the requested URL on the end (with the use of the $1
backreference). eg. A request for http://example.com/foo
would be redirected to https://www.example.com/index.htmlfoo
(in two redirects).