How to force www or non-www URLs for your domain via .htaccess

To redirect URLs on your site you can use the .htaccess files. We will show you below how to redirect non-www URLs to www URLs and vice versa.
To see more info on how to edit .htaccess files via cPanel please check this Knowledge Article.

htaccess nonwww to www
htaccess nonwww to www

To force URLs to www version use:

# Redirect non-www URLs to www URLs - like http://yourdomain.com to http://www.yourdomain.com
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.yourdomain\.com [NC]
RewriteRule (.*) http://www.yourdomain.com/$1 [R=301,L]

To force URLs to non-www version use:

# Redirect www URLs to non-www URLs - like http://www.yourdomain.com to http://yourdomain.com
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com [NC]
RewriteRule (.*) http://yourdomain.com/$1 [R=301,L]

Notice that many PHP scripts (like WordPress, Drupal, MediaWiki etc) use the .htaccess files to function properly. Don’t delete these files. Also take care when editing them.

Leave a Reply