【问题标题】:Using gzip / compression in Symfony 2 without mod_deflate在没有 mod_deflate 的 Symfony 2 中使用 gzip / 压缩
【发布时间】:2017-12-24 09:07:50
【问题描述】:

我正在处理在不同服务器上运行的两个不同的Symfony 2.8 项目。它想使用压缩来加快加载速度。我找到的所有资源都指向mod_deflate。但是,虽然第一台服务器根本不提供mod_deflate,但第二台服务器在启用FastCGI 时无法使用mod_deflate

我只找到了可以在服务器 (mod_deflate) 或“在脚本中”启用压缩的信息。但我没有找到关于这个“脚本”解决方案的任何详细信息。

是否可以在不使用mod_deflate 的情况下在 Symfony 中启用压缩?

【问题讨论】:

    标签: apache symfony http-compression


    【解决方案1】:

    您可以尝试在kernel.response 事件中手动压缩内容:

    namespace AppBundle\EventListener;
    
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpKernel\KernelEvents;
    use Symfony\Component\HttpKernel\HttpKernelInterface;
    
    class CompressionListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return array(
                KernelEvents::RESPONSE => array(array('onKernelResponse', -256))
            );
        }
    
        public function onKernelResponse($event)
        {
            //return;
    
            if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
                return;
            }
    
            $request = $event->getRequest();
            $response = $event->getResponse();
            $encodings = $request->getEncodings();
    
            if (in_array('gzip', $encodings) && function_exists('gzencode')) {
                $content = gzencode($response->getContent());
                $response->setContent($content);
                $response->headers->set('Content-encoding', 'gzip');
            } elseif (in_array('deflate', $encodings) && function_exists('gzdeflate')) {
                $content = gzdeflate($response->getContent());
                $response->setContent($content);
                $response->headers->set('Content-encoding', 'deflate');
            }
        }
    }
    

    并在配置中注册这个监听器:

    app.listener.compression:
        class: AppBundle\EventListener\CompressionListener
        arguments:
        tags:
            - { name: kernel.event_subscriber }
    

    【讨论】:

    • 非常感谢,这听起来很有希望!与mod_deflate 压缩相比,是否存在任何性能劣势?当然,gzip 是由 Apache 还是 Symfony 执行的没有区别,但是缓存呢?
    • 我不能说性能。尝试对 apache gzip 和自定义 gzip 进行测试。你可以通过 apache ab programm 来实现。我认为浏览器缓存对两个版本都是一样的。
    • 我知道这是一个老问题,但关于性能 - 这个解决方案可能有用:ustrem.org/en/articles/…
    猜你喜欢
    • 2014-01-06
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    相关资源
    最近更新 更多