Search code examples
.htaccessmod-rewritessl

Remove index.php, force ssl, and redirect www to non www in .htaccess


I appreciate these questions have been done to death, but i don't seem to be able to find the exact answer i need, all the ones closest to mine redirect non www to www but i need it the other way round.

So, what i want to do is force www to be non www at all times, rewrite the index.php out of the url, and force the site to be SSL at all times.

I have the following which does everything but force the SSL, i've tried lots of different things but always get infinite loops:

# Rewrite www to non www

<IfModule mod_rewrite.c>
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

Rewrite the index.php out

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

Solution

  • Try changing this:

      RewriteCond %{HTTPS} !=on
      RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
      RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
    

    to

      RewriteCond %{HTTPS} !=on [OR]
      RewriteCond %{HTTP_HOST} ^www\. [NC]
      RewriteCond %{HTTP_HOST} ^(?:www\.|)(.+)$ [NC]
      RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]