Web Development

Force non-www With htaccess

www In a earlier article I mentioned how to add the www. to your domain if users come through to your domain without it. Now I will explain how you can do the opposite and remove the www. from your domain if a visitors comes through with it or with any sub-domain.

Below is a snippet of the small bit of code you will need to perform this do.

Copy and paste this into your .htaccess file and it will remove any sub-domain from your domain name and redirect it to your main domain. So if a visitor types in: www.yourdomain.com blog.yourdomain.com forum.yourdomain.com

They will all get redirected to http://yourdomain.com

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

Force non-www on HTTP/HTTPS protocol.

RewriteEngine on
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]
Back to top

Gain access to all tutorials

  • Premium tutorials covering WordPress, Laravel and VueJS
  • Download premium content
  • Download premium WordPress plugins
  • Only $5 a month

Join Paulund