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 enable the rewrite engine in .htaccess?

Set PHP config Variables (like ini_set) with .htaccess

How to sort an array in javascript?

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

What is Bubble sort, and how to write an implementation of it in PHP

How to find the 2nd most common item in an array?

What does PEAR stand for?

How to split a string into an array, in JS

How to add a name prefix to all routes in a group?

How to force non www in htaccess