Using gzip / compression in Symfony 2 without mod_deflate
Asked Answered
I

1

2

I am working on two different Symfony 2.8 projects running on different servers. It would like to use compression for faster loading. All resources I found point to mod_deflate. But while the first server does not offer mod_deflate at all, the second server cannot use mod_deflate while FastCGI is enabled.

I only found the information, that one can enable compression within the server (mod_deflate) or "in script". But I did not found any detailed on this "in script" solution.

Is is somehow possible to enable compression in Symfony without using mod_deflate?

Intraatomic answered 19/7, 2017 at 8:16 Comment(0)
B
7

You can try to gzip content manually in kernel.response event:

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');
        }
    }
}

And register this listener in config:

app.listener.compression:
    class: AppBundle\EventListener\CompressionListener
    arguments:
    tags:
        - { name: kernel.event_subscriber }
Badtempered answered 19/7, 2017 at 10:43 Comment(4)
Thank you very much, this sounds very promising! Are there any performance downsides compared to the mod_deflate compression? Sure, it makes no difference wether gzip is performed by Apache or Symfony but what about caching?Intraatomic
I can't say about performance. Try to make tests for apache gzip and custom gzip. You can make it by apache ab programm. I think that browser cache works same for both versions.Badtempered
I know it's an old question but about performance - this solution might be useful: ustrem.org/en/articles/…Hacking
No more need to register the subscriber into the config file (services.yaml)Lorimer

© 2022 - 2024 — McMap. All rights reserved.