Learn how to set up an Apache mod_rewrite rule to always redirect visitors to the www version of your website for consistency and SEO benefits.
Your site can answer to two addresses, example.com and www.example.com, and to Apache those are two different sites. Pick one as canonical and send everyone to it. Here we’re forcing the www version so all your traffic and ranking signals land in one place.
Drop this into your Apache config, inside the VirtualHost or Directory block for your site (or into the site’s .htaccess):
<ifmodule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
</ifmodule>What each line does
RewriteCond %{HTTP_HOST} !^www\.fires only when the host doesn’t already start withwww., so requests that are already correct skip the rule.RewriteRulesends the request to the same path on the www host with a301(permanent) redirect. TheLflag stops rule processing there.
Restart Apache, then load the non-www address. You should land on the www version.
One thing to get right
The rule above redirects to http://. If your site runs on HTTPS, and it should, that snippet can bounce visitors down to the insecure scheme. Force the scheme too, or point the target at https://www.%{HTTP_HOST}/$1 instead.
Past that, the direction you choose is SEO-neutral. Google doesn’t favor www over non-www. What matters is that you pick one and redirect the other every single time, so you’re not splitting ranking signals or serving the same page at two URLs. If you’d rather standardize on the bare domain, flip the logic: match hosts that do start with www. and strip it.


