How can I create friendly URLs with .htaccess?

In the document root for http://website.com/ I'd put an htaccess file like this:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

Then in your PHP script you can manipulate the $_GET['url'] variable as you please:

$path_components = explode('/', $_GET['url']);
$ctrl=$path_components[0];
$id=$path_components[1];
$tab=$path_components[2];

Just tested this locally and it seems to do what you need:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/.]+)(?:/)?$ /index.php?ctrl=$1 [L]
    RewriteRule ^([^/.]+)/([^/.]+)(?:/)?$ /index.php?ctrl=$1&id=$2 [L]
    RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)(?:/.*)?$ /index.php?ctrl=$1&id=$2&tab=$3 [L]
</IfModule>

This is what it does:

  • For a path like http://website.com/pelicula/, redirect to /index.php?ctrl=pelicula
  • For a path like http://website.com/pelicula/0221889, redirect to /index.php?ctrl=pelicula&id=0221889
  • For a path like http://website.com/pelicula/0221889/posters/, redirect to /index.php?ctrl=pelicula&tab=posters
  • For a path like http://website.com/pelicula/0221889/posters/anything-can-go-here, redirect to /index.php?ctrl=pelicula&tab=posters and ignore the rest of the path.

These rewrites will work with or without a trailing slash - if you want them to work only without the slash, remove the (?:/)? from the end of the first two rewrites. You can also use mod_rewrite to add or remove a trailing slash as required.