Search code examples
.htaccesshttp-redirecthttpsrulesno-www

Redirect to non www is not working for pages in https


I am trying to add redirect rules using .htaccess for such goals:

  1. Redirect all http pages to https.
  2. Redirect all www http and https pages to non www https.

My .htaccess code:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

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

Everything is working good except one:

  • http redirects to https (all pages)
  • https www redirects to https non www (main page and subfolders)

But https://www.example.com/1/page.html does not redirect to https://example.com/1/page.html (both pages open)

What is the problem? How to write an .htaccess rule to redirect all the pages to https non www?


Solution

  • You can use this to remove www and force https:

    RewriteEngine on
    
    RewriteCond %{HTTPS} !=on [OR]
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteRule ^(.*)$ https://example.com%{REQUEST_URI} [R=301,L,NE]
    

    Make sure you clear your cache before testing this. Combing the two rules will help to speed up your website too, instead of having to run two seperate rules.