Redirect www to non www URL Using HTACCESS for WordPress

Learn to redirect www to non-www URLs or non www to www URLs using .htaccess file. You can do 301 permanent redirect on shared server with multiple domains also. If you have a self hosted WordPress website, you it would be useful for you.

mod_rewrite module of Apache server

Apache server uses modules for various functionalists. mod_rewrite is a module that enables redirection and URL rewriting. If this module is installed and available on Apache server, only then your redirection will work.

If mod_rewrite is available, it will take your redirection commands from .htaccess file.

Redirect old domain to new domain

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.olddomainname.com$ [OR]
RewriteCond %{HTTP_HOST} ^olddomainname.com$
RewriteRule ^(.*)$ http://www.newdomainname.com/$1 [R=301,L]
</IfModule>

Redirect www to non-www URL Domain

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*) http://example.com/$1 [L,R=301]
</IfModule>

Redirect non-www to www URL Domain

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [nocase]
RewriteRule ^(.*) http://www.example.com/$1 [last,redirect=301]
</IfModule>