我计划在主目录中最多添加10.htaccess重写url代码,这会影响我网站的执行(网站加载时间)吗?
我当前的.htaccess文件是
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9]+)/([0-9]+)/([^.]+).html index.php?perma=$3
RewriteRule ^movies/([^.]+).html gallery.php?movie=$1
RewriteRule ^album/([^.]+).html gallery.php?album=$1
RewriteRule ^img/([^.]+)/([^.]+).html gallery.php?img=$2
RewriteRule ^movies.html gallery.php
是的,它会影响加载时间。规则/异常越多,渲染所需的时间就越长。但是:我们谈论的是人眼甚至不会注意到的微米/毫秒。
在使用apache mod_rewrite时,您可能需要查看重写规则的顺序对性能的影响,就像@diolemo评论的那样,对于20个重写规则,这并不明显。
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();
CCD_ 5和CCD_ 6将不得不返回它们的输出。如果用$var
替换$_GET['var']
并添加输出缓冲区,那么您可能可以使用这个index.php重用现有脚本:
gallery.php
ob_start();
// ...
return ob_get_clean();
下载网页所需的大部分时间来自于检索HTML、CSS、JavaScript和图像。重写URL的时间可以忽略不计。
通常,图像是加载时间缓慢的最大原因。像Pindom这样的工具可以帮助您正确地了解各种组件的加载时间。
http://tools.pingdom.com/fpt/
HTH。