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

To redirect non-www URLs to www URLs on an Apache server using .htaccess, you can use the following steps:


RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  1. Open the .htaccess file in the root directory of the website you want to redirect. If there is no .htaccess file in the root directory, you can create one.

  2. Add the following lines to the .htaccess file:

These lines do the same thing as the ones we added to the Apache configuration file earlier: they turn on the mod_rewrite module, check if the HTTP_HOST header does not start with www., and redirect the request to the same URL with www. added at the beginning.

  1. Save the .htaccess file.

That's it! The next time someone accesses your website using a non-www URL, they will be automatically redirected to the corresponding www URL.

Note: If you already have rewrite rules in your .htaccess file, make sure to add these lines before any other rules that may affect the URL. Also, make sure to test the redirect to ensure that it works as expected.

Comments

Leave a Reply