I post this article as a kind of follow-up to my previous article “Why link to index.php?” which caused some discussion. In “Why link to index.php?” I tried to make clear that there is no need to set your home link to something like index.php. I also said that it is not good to let people decide whether they use your domain with www or without. To have some consistency and control over what URLs to use I suggested to link to the full URL.
Now I realized that linking to the full URL is not very efficient. Although I linked to the full URL, my site was in Google with and without www. That means it is 2 times in there. For instance, a result with www is #3 and another without www #14.
Suddenly I had an idea, which I hadn’t thought of before. I’m pretty sure others have, but I will explain it here.
First, you have to decide whether your website should be accessed by using www or not. I decided to use www, because it gives my domain a bit more style. It looks better. Most of you don’t like www, but it’s up to you.
You can use mod_rewrite for that; I use PHP because mod_rewrite isn’t enabled on my server. The idea is to redirect people using the “wrong” address to the “right” address. (I know you’re surprised).
if (!strstr($_SERVER["HTTP_HOST"],'www')) {
@header('HTTP/1.x 301 Moved Permanently');
@header('Location: http://www.julian-bez.de'.$_SERVER["REQUEST_URI"]);
}
This checks the “Host” header sent by the user-agent. If there’s no www in it we’ll redirect the user.
The headers will now look like that:
http://julian-bez.de/
GET / HTTP/1.1
Host: julian-bez.de
...HTTP/1.x 301 Moved Permanently
...
Location: http://www.julian-bez.de/
...
If the browser tries a request with Host: julian-bez.de the script will send a “Moved Permanently” and the new location, where the host is www.julian-bez.de.
If you use “/” as home link now, everyone will get to exactly the same URL. No www vs. non-www. URLs as you want them to be. In every search engine. On every site (okay, someone can post a “wrong” link, but if you click it you’ll be redirected). I recommend to link to every document on your website using the scheme “/example.htm”. So if you’re in the document “http://www.example.com/chapter1/page1.htm”, you should link to “/chapter1/page2.htm” to get to the next page. The first character of any internal link has to be “/”. This gives you some consistency. And consistency is always a good thing.
You need to put the code in every page. I put it in wp-blog-header.php of my WordPress installation. Here’s a version that will redirect visitors using www to a non-www URL:
if (strstr($_SERVER["HTTP_HOST"],'www')) {
@header('HTTP/1.x 301 Moved Permanently');
@header('Location: http://example.com'.$_SERVER["REQUEST_URI"]);
}