How to Force www or non-www in htaccess

Apache: How to Force www or non-www in htaccess

If you want to redirect non-www requests to the www URL of your website (i.e. redirect from http://example.com to http://www.example.com/) then you can do this with a few lines in your .htaccess file

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

Don't forget to enable the rewrite engine!

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to Force www or non-www in htaccess

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Apache language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to hide the server signature (hide Apache info) from HTTP headers with .htaccess

What are Apache MPMs?

How to namespace a Laravel route group?

How to set the timezone to UTC in .htaccess

How to prevent Eloquent from adding created_at or updated_at timestamps?

How to add the CSRF (Cross-site request forgery) token in Laravel?

How does PHP compare objects?

How to find an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

What is the null coalescing operator in PHP7?

How to select what columns to return when calling ::all()