While I do prefer to develop, any developer worth his salt is cross-trained in basic server-related tasks.
Using an .htaccess file is one of those tasks.

Since it may be only once in a blue moon that we need to add or edit an .htaccess, I always need to go back to a reference to get the syntax down. What better place to write it down than right here!

In this article I’m assuming you know how/where to place a .htaccess file and are using Apache’s rewrite module.

Remove the www Prefix

If you got here using a web search, then I am very lucky, because there are many versions of this out there already. There are more than a handful of ways to accomplish it, some better than others.

I chose the following syntax because it avoids specifying the host name like some other examples. Additionally, it does not change the protocol (HTTP vs HTTPS). Most examples you come across force it to say HTTP.

APACHEview code
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]

Adding the www Prefix

The following rewrite rule will force the URL to always have a www, if you would rather have it that way.

APACHEview code
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Solid Tip: Browsers can be finicky when testing changes to an htaccess file. It’s best to always restart or clear your cache after making changes. This will help ensure that it fetches your updated version.

BONUS: Checking for mod-rewrite

While not totally necessary, it might benefit you to simply wrap your above code in the below IF statement, just in case mod-rewrite is removed from your server at some point.

APACHEview code
<IfModule mod_rewrite.c>