I have a website that doesn\'t seem to redirect from non-www to www.
My Apache configuration is as follows:
RewriteEngine On
### re-direct t
To remove www
from your URL
website use this code in your .htaccess
file:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1$1 [R=301,L]
To force www
in your website URL
use this code on .htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^YourSite.com$
RewriteRule ^(.*)$ http://www.yourSite.com/$1 [R=301]
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule ^(([^/]+/)*[^./]+)$ /$1.html [R=301,L]
Where YourSite.com
must be replaced with your URL
.
This is similar to many of the other suggestions with a couple enhancements:
%{REQUEST_URI}
rules.The path portion not affected by previous RewriteRule
s like %{REQUEST_URI}
is.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ %{REQUEST_SCHEME}://www.%{HTTP_HOST}/$1 [R=301,L]
Try this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*) http://www.example.com$1 [R=301]
I found it easier (and more usefull) to use ServerAlias when using multiple vhosts.
<VirtualHost x.x.x.x:80>
ServerName www.example.com
ServerAlias example.com
....
</VirtualHost>
This also works with https vhosts.
<VirtualHost *:80>
ServerAlias example.com
RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>
RewriteCond %{HTTP_HOST} ^!example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
This starts with the HTTP_HOST
variable, which contains just the domain name portion of the incoming URL (example.com
). Assuming the domain name does not contain a www.
and matches your domain name exactly, then the RewriteRule comes into play. The pattern ^(.*)$
will match everything in the REQUEST_URI
, which is the resource requested in the HTTP request (foo/blah/index.html
). It stores this in a back reference, which is then used to rewrite the URL with the new domain name (one that starts with www
).
[NC]
indicates case-insensitive pattern matching, [R=301]
indicates an external redirect using code 301 (resource moved permanently), and [L]
stops all further rewriting, and redirects immediately.