Using .htaccess to Prevent www Subdomain

You can use the following rules in your .htaccess file to force users to visit your website without the www subdomain. Your users will be 301 (Permanently) redirected to the same path, but at your domain without the www.

This is a really simple thing to pull off, however I haven't seen any other websites talk about it, most people want to force users to have the www.

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

This should work with any website assuming it is hosted with Apache, and that both the normal domain and the www subdomain both resolve properly.

Thomas Hunter II Avatar

Thomas is the author of Advanced Microservices and is a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.