Search code examples
phpapache.htaccess

How to turn dynamic URL into static URL


I am developing a website using PHP and Apache. I wanna turn my URLs from

www.example.com/book.php?book=title

into something like this, if it is possible of course:

www.example.com/book/title

Notice that the title of the books are unique and cannot be repeated.

I`ve read about this, but none of the posts were clear enough for a beginner like me. Do you guys know any tutorial that explains that?

Thanks.


Solution

  • Expanding on @Rodolphe's and @Galen's replies a little bit.

    If your needs for url rewriting are limited, a hardcoded .htaccess with rules described in Rodolphe's example will do nicely.

    However, as Galen suggests, your needs may be unknown, or you may want to expand on them later, without the need to touch your rewriting rules, once you have them working.

    A common way to do it, is to design your application around a URL scheme which is www.host.com/controller/action/parameter. An example of such a URL could be www.host.com/book/view/1, which could then internally be handled in a number of ways.

    1)

    You have separate scripts for every controller. You then rewrite every request to the form $controller.php?action=$action&param=$param, redirecting non-matching or non-valid requests to a default controller.

    # Serve files and directories as per usual,
    RewriteCond %{REQUEST_URI} !-f
    RewriteCond %{REQUEST_URI} !-d
    
    # If the request uri doesn't end in .php
    # and isn't empty, rewrite the url
    RewriteCond %{REQUEST_URI} !.php$
    RewriteCond %{REQUEST_URI} !^$
    # Try matching against a param request first
    RewriteRule (.*?)/(.*?)/(.*?) $1.php?action=$2&param=$3 [L]
    # If it didn't match, try to match an action
    RewriteRule (.*?)/(.*?) $1.php?action=$2 [L]
    
    # redirect all other requests to index.php,
    # your default controller
    RewriteRule .* index.php [L]
    

    2)

    You have a single entry point (or a front controller) to which you redirect every request, and this front controller handles redirecting the request to the appropriate controller.

    # Redirect all requests that isn't a file or 
    # directory to your front controller
    RewriteCond %{REQUEST_URI} !-f
    RewriteCond %{REQUEST_URI} !-d
    RewriteRule .* index.php [L]
    

    The generic fallback rules will not append any parametes to the default/front controller. However, since it is an internal redirect, you will have access to the REQUEST_URI in PHP to determine what you should be doing.

    These are, naturally, not your only options. Just my 2 cents in the soup to stir a bit more.

    Disclaimer: All of the above rewrite rules (as well as everything else, of course) are written straight off the top of my head (after a few beers) and haven't been tested anywhere.