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 install jpegtran for Linux CentOS

How to sort an array of dates and times?

How to find the intersection (same values) from two arrays?

How to disable file hotlinking in Apache with .htaccess

How to change the order that migrations happen?

How to output (echo/print) content in PHP

How to convert a string to an array of it's characters in PHP?

How to add and remove items to an array in JS?

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

How to run an artisan command from a controller