How to redirect between non-www and www URL in Apache?

To redirect between non-www and www URL in Apache through .htaccess, you can use the mod_rewrite module. Here's how to do it:

  1. Create or edit the .htaccess file in the root directory of your website.

  2. Add the following code to the file:


RewriteEngine On

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

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

Replace example.com with your domain name.

This configuration will redirect all non-www URLs to www URLs and all www URLs to non-www URLs with a 301 permanent redirect. This helps to prevent duplicate content and improve SEO.

Comments

Leave a Reply