【问题标题】:Will RewriteRules In .htaccess Affect Site's Speed?.htaccess 中的 RewriteRule 会影响网站速度吗?
【发布时间】:2013-01-23 21:48:39
【问题描述】:

我打算在主目录中添加最多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

【问题讨论】:

  • 会有影响吗?是的。会引人注目吗?没有。
  • 通过PageSpeed Insights 运行您的网站,了解您需要担心的事情。

标签: php performance .htaccess mod-rewrite


【解决方案1】:

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.phparticle.php 必须返回他们的输出。如果您将 $_GET['var'] 替换为 $var 并添加输出缓冲,您可能可以使用此 index.php 重用现有脚本:

gallery.php

ob_start();
// ...
return ob_get_clean();

【讨论】:

    【解决方案2】:

    是的,它会影响加载时间。您拥有的规则/例外越多,渲染所需的时间就越长。但是:我们谈论的是人眼甚至不会注意到的微秒/毫秒。

    【讨论】:

      【解决方案3】:

      下载网页所需的大部分时间来自于检索 HTML、CSS、JavaScript 和图像。重写 URL 的时间可以忽略不计。

      通常,图像是加载时间缓慢的最大原因。 Pingdom 之类的工具可以帮助您了解各种组件的加载时间。

      http://tools.pingdom.com/fpt/

      HTH。

      【讨论】:

        【解决方案4】:

        您可能需要查看 performance impact of order of rewrite rules when using apache mod_rewrite 并且,就像 @diolemo 评论的那样,对于 20 条重写规则,它并不明显。

        【讨论】:

          猜你喜欢
          • 2019-09-18
          • 2014-08-03
          • 1970-01-01
          • 1970-01-01
          • 2017-02-08
          • 1970-01-01
          • 2018-07-02
          • 2021-03-25
          • 1970-01-01
          相关资源
          最近更新 更多