Search code examples
.htaccesshttp-redirectno-wwwpublic-html

How to force www. with .htaccess?


I have looked around and no one seems to be experiencing the same problem as me.

I have used:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursite.com [NC]
RewriteRule ^(.*)$ http://www.yoursite.com/$1 [R=301,L]

However when I navigate to yoursite.com I get taken to www.yoursite.com/public_html which doesn't exist.

Here is my directory structure:

/
| .htaccess
|
| public_html
    |
    |index.php

Solution

  • Try with this line :

    RewriteCond %{HTTP_HOST} !^www\.yoursite\.com$ [NC]
    

    Gumbo in his answer (how to force “www.” in a generic way?) recommanded this structure :

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