How do I do URL rewriting in php?

If you're referring to /posts/edit/522452-style URLs as opposed to /posts.asp?action=edit&postid=522452-style URLs (or whatever it translates to on the back end), this is typically done through a URL rewriter, such as mod_rewrite. A rule for that URL might look like this:

RewriteRule ^/posts/(\w+)/(\d+) /posts.asp?action=\1&postid=\2

The two primary advantages to this kind of URL are that:

  1. "Folder"-type URLs are easier for people to type and to remember.
  2. The page "looks like" a page to HTTP proxies. Traditionally, proxies don't cache pages with parameters, as they don't represent separate content and change too frequently (think search results). Using "folder-style" URLs allows them to be cached normally.

In PHP, you can then access these options via $_GET['action'] and $_GET['postid'], exactly as if the browser had asked for the rewritten form.


To use such URLs you have to do three steps:

  1. Tell you webserver, that those requests should redirected to your PHP script. With Apache you can use the mod_rewrite module to do so:

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule !^index\.php$ index.php [L]
    

    This directives redirect every request, that does not match a file in the filesystem, to index.php.

  2. Get your script to parse those URLs:

    $_SERVER['REQUEST_URI_PATH'] = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
    $segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
    var_dump($segments);
    

    This is probably the easiest way to parse the URL path and get each path segment.

  3. Use this URLs in your output. (trivial)


A part for SEO purposes, caching and readability, as others have pointed out, I would like to add that folder-style parameters are also an incentive for users to "play around" with parameters. For instance here on Stackoverflow it is often tempting to edit the url by hand when filtering by tags, instead of looking for the appropriate button and clicking on it.