It is useful to make your website available both with and without “www” as url prefix, in order to bring in people not sure about your exact url.
However, it would also impact your SEO, as search engine will consider both urls as distinct sites, each taking half of the fame.
A common solution is to have one of the url redirected to the other one – the search engines understand the corresponding HTTP “redirect” and consider that the two urls are n fact the same site.
DNS configuration
You first need to setup your DNS records, to have both url
mydomain.tld
and
www.mydomain.tld
pointing to the IP of your web server.
Apache configuration
An easy way to do this redirect with Apache is to define two VirtualHosts, as follow (here the www is redirected to the non-www):
NameVirtualHost *:80
<VirtualHost *:80>
ServerName mydomain.tld
ServerAdmin admin@mydomain.tld
DocumentRoot /path/to/my/web/folder/
</VirtualHost>
<VirtualHost *:80>
ServerName www.mydomain.tld
RedirectMatch 301 (.*) http://mydomain.tld$1
</VirtualHost>
So here two virtual hosts are defined.
The requests “mydomain.tl”, matching the ServerName defined in the first VirtualHost, will get served the files defined in the corresponding DocumentRoot directive.
The requests “www.mydomain.tld”; matching the ServeName defined in the second VitualHost, will inform the browser that the url it requested is permanently redirected to the url without www.
So for example; if a browser sent a request to http://www.mydomain.tld/about.html, the Apache server will tell the browser that this page is now to be found at http://mydomain.tld/about.html.
More details on the corresponding apache directives
NameVirtualHost is the IP (and possibly port) of the requests to be served by the VirtualHosts.
So if your servers has only one IP address, or if all the IPs have to be served by the VirtualHosts, you can use * (as in this example)
The argument of the <VirtualHost> directive must match with the NameVirtualHost value.
ServerName is the value the server tries to match with the requested url. If it matches, then the configuration defined in the corresponding VirtualHost is used.
DocumentRoot is the webroot folder path.
RedirectMatch redirects using regular expressions (requires mod_alias). Matches the url path (exclude the domain.tld)
In our example:
- matches any url path “.*”
- captures the path (thanks to the braces)
- redirect to mydomain.tld/theMatchedUrlPath ($1 means the string matched within the braces)
Sources
http://httpd.apache.org/docs/2.2/en/vhosts/name-based.html
http://www.301-redirect.net/fr/ [french]