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 round a number in JS?

What is YAGNI?

How do you run a PHP script from the command line?

How to show a specific view file for certain error codes?

How to enable the rewrite engine in .htaccess?

What are macros in Laravel?

How to block an IP address in .htaccess

How to exclude URLs from the Laravel CSRF protection?

How to force SSL in Apache's .htaccess?

How to find out what version of Laravel you are using?