Force www. in your URL using .htaccess

Insert this into the top of your .htaccess file, making sure that ‘RewriteEngine On’ comes before it:

RewriteCond %{HTTP_HOST} !^ [NC]
RewriteRule ^(.*)$ [R=301,L]

Replace with your chosen domain and make sure if you are placing any full stops within the first line to enter a backslash before each full stop. This will prevent the code from not working.

13 Responses

  1. Ryan Christensen

    I tend to prefer the reverse (something about the URL length, I think.) Either way, great tip!

    Is there a reason you prefer having the “www” over the alternative?

  2. Jamie Huskisson

    Think I’ve seen it for so long it just feels un-natural without it Ryan ;)

  3. Maciej Pawłowski

    But it’s quite bad idea … Instead try:
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^$ [NC]
    RewriteRule ^(.*)$ [R=301,L]

  4. Jamie Huskisson

    So instead of adding the www. your code removes it Maciej?

    Thanks for contributing that – I’m sure people here will be looking for both alternatives :)

  5. Daniel

    I’ve tried both, but the solution has caused other problems. I’ve installed bbpress, but the users that log into Skinplistic WITHOUT the www are not recognized by users that log into bbpress WITH the www. I used the code above to force access via www, however; I noticed this counted multiple hit against my server (I use slimstat). Plus, I think it may be upsetting adsense and the other robots I prey for everyday. ;) I don’t know what to do.

  6. kyle renfrow

    this solution provided is only for http, make sure you cover https as well..heres the code I’ve been using for quite some time:

    RewriteCond %{HTTP_HOST} ^
    RewriteCond %{HTTPS} =on
    RewriteRule .* https://www.%{SERVER_NAME}%{REQUEST_URI} [R,L]
    RewriteCond %{HTTP_HOST} ^
    RewriteCond %{HTTPS} !=on
    RewriteRule .* http://www.%{SERVER_NAME}%{REQUEST_URI} [R,L]

  7. Camaron

    #kyle renfrow

    thank you, the other redirect chops the path before the script name off (in my case at least)

  8. Jim

    Thanks Jamie and Maciej for the simple documentation. I’ve referred to it several times myself.

  9. Ernie

    Thanks for this, I’ll get it up on my site now :)

  10. Pingback on

  11. Toyin

    HI this is my current .htaccess file. The solution above doesnt seem to work for me. the site doesn’t load up when I have made the changes. what am I missing? thanks

    # BEGIN WordPress

    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    # END WordPress

  12. Andy

    Many thanks for this – I’ve used it successfully on my site.

  13. igi

    @kyle renfrow
    Thanks for your suggestion!!! IT ROCKS DUDE!!!

Comments are closed, but feel free to @jhuskisson on Twitter with your thoughts.