URL rewriting with Apache’s mod_rewrite
February 4th, 2006 by Robert KrennUnfortunately, too many webdevelopers are still not familiar with the concept of URL rewriting. And many that did come in touch with Apache’s mod_rewrite, often do not use many of its powerful features, or even put it aside completely because of its relatively high complexity
While the learning curve of URL rewriting might be steep, especially for those who are not used to writing regular expressions, the control it gives you over your website is well worth the effort. With URL rewriting, you can redirect and rewrite an incoming page request to virtually anything. This can be used to present users a completely different page or send them to another webserver, change the URL in the browser window, create shorter and easier URLs without modifying your backend and it can even be used as a basic form of input filtering for your scripts.
To use URL rewriting, you have to enable the RewriteEngine first. This can be done in your httpd.conf or in a .htaccess file on a per directory basis. After you have done this, you have to define rewrite rules. These rules can contain regular expressions, environment variables and even conditional statements, giving complete freedom to rewrite your incoming requests. All matching rewrite rules will be executed from top to bottom (unless this behaviour is limited with the last flag).
Why bother?
As your website is most likely working just fine without URL rewriting right now, you might ask yourself why you should bother with learning and implementing this complex feature. Well, there are actually several answers to that question.
One of the most important reasons to use URL rewriting are search engines. While most dynamic websites work perfectly fine in webbrowsers, search engine crawlers work a little different. When a webbrowser requests a script, specifying parameters in the URL, they get a nice page in return. Some webcrawlers omit the parameters and just request the script file however. In many cases, not specifying any parameters will result in an error message , which is then parsed and indexed by the search engine, instead of your content. Not all search engines act as simple as this, but a fair amount of them will still assign a lower rank to dynamic content because it often changes or is temporary data.
Another advantage of rewriting is the ability to create shorter URLs that are easier to remember. For example, instead of having to enter a long and obfuscated URL like this: http://www.example.com/catalogue.cgi?category=sports&sub=tennis&article=racket01, you could define a rewrite rule that would let you enter http://www.example.com/catalogue/sports/tennis/racket01 instead. This eliminates all redundant data in the URL, which will be defined in the rewrite rule. The webserver will redirect the user internally to your original catalogue.cgi, so there is no need to change your modify anything in your current script code. URLs like the above are not only easier to remember, but they appear to be static content too, resulting in better search engine ranking.
URL rewriting can be very useful in a less occuring case as well. When you have created a completely new website with new ways of managing your content, quite often your URLs change as well, rendering visitors bookmarks and search engine indexes useless. With rewriting, you can now map the old content URLs to your new site. Optionally, you can even specify a 301 Moved header, so browsers and webcrawlers will know the content has moved to a new location and that they should update their resources. By doing this, you can make sure your visitors will still find the information they are looking for.
One other use of URL rewriting is not very well known and even less used in practice, but it can still be a good addition to your site. Using rewrite rules, you can implement a basic form of input filtering for your scripts using regular expressions. By using this functionality you can make sure that your script, when placed outside your webroot, will only receive certain input types. For example, you could write rewrite rules that will match only integers, strings, zipcodes, phonenumbers, or bankaccount numbers at certain positions in your URL. Because the rule will only match the request when valid input is received, and therefore will only be executed in that case, your script will never receive invalid data at all. This is a fairly easy way of placing extra input checking on third-party products or other situations in which you might not have full control over the source code, adding to the general security level of your site.
To conclude, URL rewriting is a very powerful tool that every webdeveloper should be familiar with, as it offers many advantages to create better websites. While learning and understanding the concept might cost you some time, it will definitely be worth the effort. If there is any demand, I may write up some examples, including code, in a next article.
Related posts
No related posts.
February 5th, 2006 at 7:54
Nicely written piece Robert. Another reason for using mod_rewrite is the aspect of usability. It (can) give people the chance to guess their way around a site. If you look at the url for this page for example, and you take of the last bit, you’ll go to an overview page of everything that’s on that date. Ie. you can simulate a directory structure that doesn’t exist and give people another easy way to get around your site.
So in the example above ‘http://www.example.com/catalogue/sports/tennis/racket01 ‘ you could guess your way to a page with all tennisrackets on it.
February 19th, 2008 at 10:38
Although I have found your article well done I disagree; the real reason fo so heavy use of mod_rewrite is one:
google !!
there are no reason to rewrite anything, dynamic pages are perfect and because of google we are returning to static page only for it as live.com work fine.
fedup
March 24th, 2010 at 7:20
Hi!
Finally I managed to find a site on such subjects! And it is part this is the place.
Here, I’ll probably frequent visitor, as the 6 hours spent searching.
April 25th, 2010 at 10:55
Only, http://airlinediscountticketmilitary.yolasite.com airline discount ticket military, 2696,
April 25th, 2010 at 5:57
What is it, http://coachhandbagscheap.yolasite.com Real coach handbags, ktn,
April 28th, 2010 at 3:26
Only, http://powerwheelchair.tumblr.com/ power wheelchair for you, ehk,
May 16th, 2010 at 4:52
Greetings, are a wonderful site for acquaintances, at first concerned this invention sceptically, but have risked to come, have got acquainted with the girl, already as 3 months we meet, we think of wedding, come you will not regret - [url=http://yourcockisgood.ru/map.html]Dating Site[/url].
July 6th, 2010 at 9:19
[url=http://russian-brides-best.com/]ukrainian brides[/url]
July 27th, 2010 at 9:07
Без салонов красоты и студий загара сложно представить нашу жизнь. Мы уже сами, не осознавая происходящего, регулярно посещаем студии загара, пользуемся услугами салонов красоты. Если нам предложить отказаться от данных услуг, мы испытаем как минимум шок…
А что бы его не испытывать есть[url=http://baseall.ru] Рейтинг SPA[/url]
July 28th, 2010 at 3:52
Проект Студия загара является эксклюзивным порталом в отрасли загара. Портал является структурированной системой объединяющей студии загара, и предоставляющей объективную оценку работы салонов. Объективность оценок в первую очередь достигается с помощью ваших отзывов и оценок студий загара.
July 29th, 2010 at 1:10
Sodeuphodieds
Интересные новости и не только в [url=http://livjurnal.ru]livjurnal[/url]
Idiomaessette