How do you redirect HTTP to HTTPS and remove .html in the same rewrite rule?

Viewed 57

Is there a way that we can remove .html file extension and move http to https in the same redirect rule so that we do not have multiple redirect chain on the same page.

http -> https -> remove .html

this leads to take more loading time and also has two redirects.

here is htaccess:

RewriteEngine on
#force https+www
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule (.*) https://www.%1/$1 [L,R=301,NC]
ErrorDocument 404 /404.html


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

You can use a single redirect rule like this:

ErrorDocument 404 /404.html
RewriteEngine on

#force https+www and remove .html
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\. [OR,NC]
RewriteCond %{THE_REQUEST} /[^.\s]+\.html [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(.*?)(?:\.html)?$ https://www.%1/$1 [L,R=301,NC]

RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule ^(.+?)/?$ $1.html [L]
Related