Site Cloner PHP Script
Bargain Hunter PHP Script
Job Hunter PHP Script
Site Login and Access Control PHP Script

Remove www From URL with .htaccess

For whatever reason, the time could arrive when you would like to remove www from urls from your root website folder or a subdirectory. If you use the Apache server, mod_rewrite makes it easy for you to do this procedure.

The methods below show one example you could use in your root folder and another you could use in any subfolder which has its own .htaccess file. The examples will have the blocks for both http and https urls.

The first block of code below will be added to any .htaccess file where you want to make the custom rewrite conditions and rules.

The code between the <IfModule mod_rewrite.c> and </IfModule> tags is interpreted if the mod_rewrite module is enabled on the server. Usually, it is always enabled. Although the other blocks of code are outside of the mod_rewrite folder, they will be interpreted.

<IfModule mod_rewrite.c>  
Options +FollowSymLinks 
RewriteBase / 
Options +FollowSymLinks 
</IfModule>

Root Folder

HTTP

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

HTTPS

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

Subfolder

HTTP

 # remove www 
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] 
RewriteRule ^ http://%1%{REQUEST_URI} [NE,R=301,L]

HTTPS

 # remove 
www RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] 
RewriteCond %{HTTPS} =on 
RewriteRule ^ http://%1%{REQUEST_URI} [NE,R=301,L]

For more information about mod_rewrite variables, you can see them at http://www.askapache.com/htaccess/mod_rewrite-variables-cheatsheet.html

More mod_rewrite Theory

Although you can move on and just add the code as it was described above, I will add a little theory into the mix.

The actual file mod_rewrite.c is C source code. You could find this file with command find / -name ‘mod_rewrite.c’ 2>/dev/null. If you wanted to check it out, you can view it with the cat command or load it into an editor. At this point, you may want to have a tuner on the language C, so that you will know more about pointers, global scope, and libraries. It is very different and more head spinning than a scripting language like PHP.