Search code examples
php.htaccessurl-rewritingvanity-url

How to rewrite URL using Apache


I have a simple question, but I couldn't find the way to do it in my script.

Instead of this:

http://www.mySite.com/player.php?id=3773

I need this:

http:/www.mySite.com/europe/spain/real-madrid/cristiano-ronlado/

Solution

  • There are examples and tutorials all over the internet for this, you just need to search for the right keywords. Some examples:

    1. Vanity URL's
    2. Clean URL's
    3. .htaccess rewrites
    4. SEO friendly URL's

    One site that I found helpful when learning about .htaccess rewrites was this one:

    http://corz.org/serv/tricks/htaccess2.php

    and a more friendly one:

    http://net.tutsplus.com/tutorials/other/using-htaccess-files-for-pretty-urls/

    It teaches you the basic stuff, but also goes into the deeper more complex stuff.

    Useful Tip

    One thing that is very important, otherwise you will run into issues with linked files, is to use absolute links in your HTML.

    So instead of this:

    <link rel="stylesheet" href="/css/stylsheet.css" />

    You need to specify the whole address like so:

    <link rel="stylesheet" href="//example.net/css/stylsheet.css" />

    The reason why the above is necessary is because you are telling the server to interpret example.net/blah/blah/blah/ as example.net/blah.php?id=123, but the browser only sees it as example.net/blah/blah/blah and therefore the relative links get broken.

    UPDATE

    One additional thing to mention is that whilst this is handled server side, it is not PHP that handles the rewrite, it is Apache.