10 rules are not a problem, but for future reference: The usual approach is to redirect everything to a single entry point and let the application do the routing. A simple example:
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L,QSA]
index.php
$query = $_SERVER['REQUEST_URI'];
$queryParts = explode('/', $query);
switch($queryParts[0]) {
case 'movies':
// ...
break;
case 'album':
// ...
break;
case 'img':
// ...
break;
// ...
default:
// 404 not found
}
The RewriteCond
conditions assure that requests to existing files are not rewritten. QSA is optional, it means "query string appended", so that for example movies.html?sort=title
gets rewritten to index.php?sort=title
. The original request URI is available in $_SERVER['REQUEST_URI']
.
If your application is object oriented, the Front Controller pattern will be of interest to you. All major PHP frameworks use it in some way, it might help to look at their implementations.
If not, a micro-framework like Silex could do the job for you. In Silex your routing could look as follows:
index.php
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
$app->get('/{year}/{month}/{slug}', function ($year, $month, $slug) use ($app) {
return include 'article.php';
});
$app->get('/movies/{movie}.html', function ($movie) use ($app) {
return include 'gallery.php';
});
$app->get('/album/{album}.html', function ($album) use ($app) {
return include 'gallery.php';
});
$app->get('/img/{parent}/{img}.html', function ($parent, $img) use ($app) {
return include 'gallery.php';
});
$app->get('/movies.html', function () use ($app) {
return include 'gallery.php';
});
$app->run();
gallery.php
and article.php
would have to return their output. You probably can reuse your existing scripts with this index.php if you replace $_GET['var']
with $var
and add output buffering:
gallery.php
ob_start();
// ...
return ob_get_clean();