I just registered a new domain name for this site, and then I needed to rewrite the old URLs to the new name. This is quite easy since I have a Linux server (CentOS in fact) with Apache. I wanted to tell the browsers and search engines that the new domain name is a permanent one and therefor the correct redirect is called a 301 server-side redirect. What this in simple terms means is that the web server will tell the web-browser or search engine spider that “this site has moved, and the new permanent address is: www.sbarmen.no”.
To implement this I used a RewriteMod command in my .htaccess file located in the websites root directory. For this redirect I wanted to move from:
http://stian.barmen.nu OR http://www.stian.barmen.nu TO http://www.sbarmen.no.
Simple ey? Yes in fact it is. Just open the .htaccess file and add these lines to the top of the file:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !www.sbarmen.no$ [NC]
RewriteRule ^(.*)$ http://www.sbarmen.no/$1 [L,R=301]
The first line just tells Apache to make sure the rewrite engine is turned on, you could also prefix this with a <IfModule mod_rewrite.c> and suffix with <IfModule> and you would not get any errors in your logs og tre moduler SAS not loaded, but the long and short of it is, make sure Apache loads the mod_rewrite module in the configuration file (and most default apache installations does).
Explanation to the above rules is that the RewriteBase just tells it will rewrite for all URLs on this site, the second RewriteCond checks that the domain name requested from the requestor is NOT www.sbarmen.no (the ! is the NOT part) and the [NC] means case insensitive. Lastly the RewriteRule itself, for all characters in the URL string following the domain part ^(.*)$ modify the domain part to http://www.sbarmen.no and then add the content of the ^(.*)$ afterwords, this is the $1. First part captures the non-domain URL part, and the we add it to the new URL. This means that all requests on sub-pages will also work without any issues.
So finally, the L,R=301, in short this is where we say to Apache the this rewrite is done (L) and now send a redirect that is a permanent move for this site, R=301. So next time please use the www.sbarmen.no and all of this rewrite business will be omitted.
That was a very geeky way to explain that I have moved this site to a new domain name, so thanks for reading 🙂
Sources:
Apache Mod_Rewrite: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
Wikipedia HTTP Redirects: http://en.wikipedia.org/wiki/URL_redirection#HTTP_status_codes_3xx
Recent Comments