Last Updated on April 15, 2021 by Amit

Enforce www using RewriteRule in htaccess

htaccess redirect non-www to www

In this post I will show you how to redirect a non-www domain to www using RewriteRule directive in htaccess or server.config files.
The following is a simple and basic rule to enforce www on a domain. You can add this to your htaccess in document root folder.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) https://www.example.com/$1 [NC,L,R=301]

You will need to replace “example.com” with your own domain name to use this rule.
This will redirect example.com and all its paths to www.example.com with whatever URI was requested.
Why I call it simple is because you just need to replace the domain name and code becomes fully functional on your domain. The syntex of the rule is easier to understand.

Here is line by line explanations of the rule :
RewriteCond %{HTTP_HOST} ^example.com$ [NC] This line checks to see if the host header is exactly example.com if yes.. then the condition becomes true and sends a green signal to the rule.
RewriteRule (.*) https://www.example.com/$1 [NC,L,R=301] The RewriteRule lines executes only if the RewriteCond is true. The pattern (.*) matches all URIs of “example.com” domain and redirects them to “www.example.com” . The $1 is a backrefrence. This includes the value captured in regex (.*) , for example: when the request is “example.com/foobar” the value the regex capture-group (.*) will capture is foobar and it will be saved in $n so that it can be used in substitution string.
[NC,L,R=301] are the mod rewite flags.
L means Last. This tells server to stop reading more rules if this one matches.
NC flag is used for ignoring character case. With this flag you can use both upper-case and lower case characters in URIs.
R=301 flag tells server to make a permanent redirection of the URLs with 301 HTTP redirect status

Rule for server.config file

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) https://www.example.com$1 [NC,L,R=301]

The only difference between the rule for htaccess and the server.config files is the “destination of the rule” . As you can see here we trimmed the / traling slash that was right after the domain name in the substitution string. The reason why it is removed is because server.config uses an absolute path starting with / in RewriteRule. So the (.*) in RewriteRule captures URIs with a leading slash. For example if the requested URL is “example.com/foobar” then the regex pattern in RewriteRule in server.config context will save /foobar in $1 variable.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.