10個規則不是問題,而是供將來參考:通常的做法是將所有內容重定向到一個入口點並讓應用程序執行路由。一個簡單的例子:
的.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
}
的RewriteCond
條件確保請求現有的文件不會被改寫。 QSA是可選的,它表示「附加查詢字符串」,因此例如movies.html?sort=title
被重寫爲index.php?sort=title
。原始請求URI可在$_SERVER['REQUEST_URI']
中找到。
如果您的應用程序是面向對象的,則Front Controller模式將會引起您的興趣。所有主要的PHP框架都以某種方式使用它,這可能有助於查看它們的實現。
如果不是,像Silex這樣的微觀框架可以爲你做這項工作。在Silex的你的路由可以看看如下:
的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
和article.php
將不得不回它們的輸出。你或許可以用這個index.php文件重用現有的腳本,如果更換$_GET['var']
與$var
並添加輸出緩衝:
gallery.php
ob_start();
// ...
return ob_get_clean();
這會對產生影響?是。它會顯着嗎?沒有。 – diolemo
通過[PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights)運行您的網站,瞭解您需要擔心的事情。 –