1. URL beauty with mod_rewrite

    27 ноября 2005


    Last years it is become a tradition to have beautiful URLs on your site, like /news/22/ and not /index.php?mod=news&day=22. The beginning of beautiful URLs is deep into major corporation portals history. Their usability specialists decided to make URLs cleaner because of people are frequently typing an URL instead of using hyperlinks. That was a good decision.

    Many URL beatifying techniques were developed by web-specialists since that. So, let's do a little overview.

    Way 1. The simplest way.

    Remember how directories are represented in URL. Got it? /site_address/dir/. Now remember that when we are typing an URL server gives us index.html (or another index) in that directory. But we weren't typed it!

    That's the first solution: create some directories to represent URLs and an index.html for each directory.

    So now we can have our page previously available at /book.html at a new URL: /book.

    No additional coding required! But… those directories… What's more we can't specify script GET parameters in a beautiful way. It will be like /book?name=fight_club.

    Way 2. Apache server settings.

    It is possible to tune up Apache so it will search some likewise files when it can't find the one specified. So the directories aren't necessary anymore… but parameters problem is still here plus we have a new problem: Apache can do some mistakes and give user a wrong file.

    Way 3. Files without extension.

    The following .htaccess trick can make files without any extension executable:

    ForceType application/x-httpd-php

    So Apache mistakes problem is solved. But we still need to pass some parameters and editing files without extension is not so handy.

    Way 4. Error redirection.

    One more trick with .htaccess file. All user queries to the files that aren't exists are redirected to index.php.

    ErrorDocument 404 index.php
    ErrorDocument 403 index.php
    ErrorDocument 401 index.php

    Now we can use $REQUEST_URI variable in our script, parse it and do something based on it.

    Tip: to get normal server reply (by default it will be 404: Not found) you must send following header in the beginning of each page:

    header('HTTP/1.0 200 Ok');

    It's a great solution in comparison with previous ones but you must write plenty of code that's not so good at all.

    Are there any solutions left?! Yes!

    Way 5. The cure-all solution.

    When I was writing first version of RMCreative engine I decided to use beautiful URLs. As a lazy programmer I used Google first to find ready to use cure-all solutions. But no solutions were really cure-all :(. With one you can do only simple things, with another you must write a lot of code…

    Then I found an article by Dmitry Lebedev, who wrote about Apache mod_rewrite module and how to do beautiful URLs with it. It is a great article but it was so much like my ways 4 with code writing…

    So, I found how to use mod_rewrite better.

    What is mod_rewrite?

    mod_rewrite is an Apache server module that is already enabled in 90% of all servers. It is adding URL preprocessing features to Apache. It's handy to use .htaccess file to specify some rewrite rules.

    First you need to turn on rewrite module: RewriteEngine On

    Then we can specify a rule: RewriteRule source (user) URL final (script) URL

    When user types http://example.com/source_URL/ server gives http://example.com/final_URL/ as a result.


    RewriteEngine On
    RewriteRule news/ news.php
    RewriteRule files/book/ files.php?id=book

    But it's only a little part of mod_rewrite features!

    The main feature is that we can use regular expressions!

    If you aren't so familiar with regular expressions I recommend you to read about them first. As first sight they have no meaning at all but later you will certainly say "it's the best tool to do something with a string".

    You can find some kind of description in php manual but it's better to find some other sources.

    Ok, let's go forward.

    Let's suppose we wrote a script that displays an article specified. This script can be accessed with URL like this:


    This is totally bad for us. We want something like:


    No problem! Open your .htaccess and write:

    RewriteEngine On
    RewriteRule ^article/([^.]*)[/]?$ showarticle.php?article=$1

    That's it.

    Another great mod_rewrite regular expressions feature is that we can accept only certain type of data.

    Let's assume we need to display news for year 2004. URL for this script is news.php?year=2004, but some bad guys can write something like this: news.php?year=-23. We can write some code to handle this but also we can use mod_rewrite instead:

    RewriteEngine On
    RewriteRule ^news/([0-9]{4})[/]?$ news.php?year=$1

    In this case we can enter only 4 digits number: news/2004/.

    Now if we try to enter news/-23/ server gives us 404 error(document not found). That's exactly what we need.


    Finally we got an URL replacing method that doesn't require a single line of code. This method can be easily applied to already written application. Additionally we got one more solution to guard our script from those "bad guys" ;)

    Perhaps, the only disadvantage of this method is that we need to learn regular expressions. But it won't be waste of time because they could be used almost everywhere to do wonderful things on strings.

  2. Библиотека веб-программиста

    25 ноября 2005

    Сравнительно недавно Naruvi запустил замечательный проект - Библиотеку веб-программиста WEBZ. На сайте собраны отборные статьи на тему web-программирования. Каждый желающий может с лёгкостью добавить ссылку на свои статьи.

  3. Любителям Winamp

    25 ноября 2005

    Сегодня я выкладываю на суд общественности все свои пресеты для Winamp AVS.

    Слушайте музыку, наслаждайтесь жизнью и смотрите.

  4. Ruskiy требуется хостинг

    25 ноября 2005

    Ищется спонсорский хостинг для размещения материала с http://ruskiy.com.ru/.

    Писать на почту, которую можно найти на вышеприведённом сайте.

    Всем откликнувшимся спасибо.

  5. Вести от Ruskiy

    15 ноября 2005

    Номер один:

    Готовится к выходу новая версия Ruskiy Web Wint 1.2 beta. Если кто не видел что это такое, то вот ОТСЮДА можете скачать предыдущую версию. Новая версия также не будет требовать MySQL.

    Номер два:

    Закончена работа над новой 1.3 (пока что Beta) версией Гостевой Книги. Для работы скрипта требуется PHP + MySQL, установщик находится в папке install гостевой. Дополнительная Справочная информация будет доступна, после выхода Официальной 1.3 версии, после исправления всех найденых БАГов.

    В общем заходим к Ruskiy и знакомимся с его замечательными скриптами.

  6. F.E.A.R.

    6 ноября 2005

    Всё ещё под впечатлением от этой великолепной игры. Пару раз даже не на шутку испугался. Последний раз такое было когда в первый Half-Life играл.

    Пожалуй, самая стоящая за последний год.

    Играть всем поголовно.

  7. Quake2: Lost Marine портируется под Q4

    6 ноября 2005

    Порт Quake2 под Doom3 портируется под Quake4 :) Ну, в общем, думаю, понятно.

  8. Немного юмора

    5 ноября 2005

    Кирпич вращается вокруг главного корпуса (университета) – давайте рассмотрим эту типичную ситуацию…

    Читаем дальше...

  9. Новая Опера быстрее всех

    27 октября 2005

    Новая 9-я версия работает в разы быстрее восьмой и обгоняет по скорости абсолютно все существующие браузеры. Видно даже на глаз.

    Не верите? Попробуйте сами.

  10. Предфинальная версия КВАДРАТа

    23 октября 2005

    Залил предфинальную версию сайта интернет-кафе "КВАДРАТ".

    Скорее всего такой она останется.