.htaccess redirects to remove php and redirect to https and non-www

Viewed 1004

I have the following in my .htaccess file to

  • Remove www
  • Redirect to https
  • remove .php

This is my .htaccess:

# ----------------------------------------------------------------------
# | Redirect to HTTPS & remove www                                     |
# ----------------------------------------------------------------------
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301] 

# ----------------------------------------------------------------------
# | Remove .php extension                                              |
# ----------------------------------------------------------------------
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]

When I view the site in Firefox I get the following error:

The page isn't redirecting properly. This problem can sometimes be caused by disabling or refusing to accept cookies

And Chrome warns about too many redirects

The URL is updated to what I would expect (www removed and https added). There are no other redirects in effect

Can anyone spot where I am going wrong?

2 Answers

It looks like you will want the following in your .htaccess file:

# ----------------------------------------------------------------------
# | Redirect to HTTPS & remove www                                     |
# ----------------------------------------------------------------------
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR]
RewriteCond %{https} off
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

# ----------------------------------------------------------------------
# | Remove .php extension                                              |
# ----------------------------------------------------------------------
RewriteRule ^(.+)\.php$ /$1 [NC,L,R=301]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)/?$ /$1.php [END]

This was borrowed from the accepted answer to the following similar topic:

.htaccess - Remove www, force https, remove php and remove trailing slash

Try below code in your .htaccess file:

RewritEengine on
Options +FollowSymlinks
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://example.com/$1 [r=301,nc]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Related