Nothing is quick and easy.
Setup
First you must make sure that you have the package installed
To use mod_rewrite, you need to load the extension. Usually, this is done by inmporting the rewrite.so module in the apache2 global configuration (/etc/apache2/apache2.conf
)
Usually all mod_rewrite instruction are written in the virtual host definition. (Say: /etc/apache2/site-available/000default
)
Usage
First step
To enable rewrite for one site, you have to ask for it with :
RewriteEngine On
Then you can begin to write rules. The basic you need to write rules is describe by the following diagram :

(See also : How does url rewrite works?)
To help me understand how it works, always consider it from the server side (not client side).
You receive an URL from the client. This URL has a certain format that you had defined. (E.g. http://blog.com/article/myarticle-about-a-certain-topic
). But apache can't understand this by himself, so we need to help him. We know that the controller is page.php
and can look up article by name.
Getting information
So now we forge a regex
to extract information from the URL. All regex are matched against what is following your domain name (here : article/myarticle-about-a-certain-topic
without the first /
-- It can be written though on recent version of rewrite)
Here we need the article's name: ^article/(.*)$
will do the job of matching URL against article/<something>
and capturing <something>
into $1
. (For characters meaning, I advise you to look a tutorial on regex. Here ^ is beginning of the string, invisible position after the .com/
, and $ the end of the URL)
So now we need to informe apache that this URL means http://myblog.com/page.php?article=myarticle-about-a-certain-topic
This is achieved by using a RewriteRule
RewriteRule ^article/(.*)$ page.php?article=$1
Restricting to conditions
To go a bit on advance topics, you may want to apply this rule only if the article name is fetch by GET method. To do this, you can include a RewriteCond
like
RewriteCond %{REQUEST_METHOD} GET
It goes BEFORE a RewriteRule
in the file but is tested AFTER it.
Flags
If you are making lot of redirection/rewrite, you will have to understand flags
The most used are [L]
and [R]
. A little explanation on those :
[R]
ask for redirection, it can be tuned like [R=302]
where 302 is a redirection status number of the HTTP protocol. This will force the client to make a new request with the rewritten URL. Therefore he will see the rewritten URL in his address bar.
[L]
forces apache to stop treating rules. Be advise that it does mean that the current incoming URL will stop being modified, but the rewritten URL WILL go again through the process of rewriting. Keep this in mind if you want to avoid loops.
Conclusion
So you end up with the following block of instructions
RewriteEngine On
RewriteCond %{REQUEST_METHOD} GET
RewriteRule ^article/(.*)$ page.php?article=$1
See also
You can find additional resources here :