Search code examples
regexapache.htaccesshttp-redirectmod-rewrite

.htaccess allow both www and non-www


I have subdomain that can be accessed like https://sub.example.com but if I do www.sub.example.com it returns

Server Not Found

Currently without any .htaccess file if I type sub.example.com it goes to https://sub.example.com I want the same thing happen if I type www.sub.example.com

Any idea?


Solution

  • Could you please try following.

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


    OR if every request has to be https and without www then better we could try.

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