Reputation: 145
I have gone through a lot of articles on 301 redirects(.htaccess), but haven't found any which could help on all 3 redirects as I mentioned in the title of this question (http to https + www to non-www + 'index.php' to '/').
What I have tried so far(but unable to achieve the desired result):
.htaccess file
RewriteEngine on
#redirect http to https plus www to non-www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
#RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI} [NE,L,R=301]
#redirect /index.php to /
#RewriteRule ^index\.php$ / [L,R=301]
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 year"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(js|css|xml|gz)$">
Header append Vary: Accept-Encoding
</FilesMatch>
</IfModule>
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
This works fine, only when it comes to http
to https
, but all three redirects don't work at once, If I try different-different solutions, I get Error Too many redirects
Upvotes: 1
Views: 144
Reputation: 41219
You can use the following htaccess
RewriteEngine on
#redirect http to https plus www to non-www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI} [NE,L,R=301]
#redirect /index.php to /
RewriteRule ^index\.php$ / [L,R=301]
Edit :
If you are using cloudflare
then you will need to replace the %{HTTPS}
variable with Cloudflare url scheme check variable %{HTTP:CF-Visitor}
.
Replace this line
RewriteCond %{HTTPS} off [OR]
with
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' [OR]
Make sure to clear your browser cache before testing this change.
Upvotes: 1
Reputation: 4302
Try this :
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]
RewriteRule ^index\.php / [R=301,L]
The rules above will match both https://www
and http://www and all http://
and force them into https://without-wwww
and also will ignore only https://without-www
.
last line will remove index
in URI.
Note: clear browser cache the test
Upvotes: 0