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?

Andrei Herford
  • 17,570
  • 19
  • 91
  • 225

1 Answers1

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 }
Max P.
  • 5,579
  • 2
  • 13
  • 32
  • 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? – Andrei Herford Jul 19 '17 at 12:04
  • 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. – Max P. Jul 19 '17 at 12:22
  • 1
    I know it's an old question but about performance - this solution might be useful: http://www.ustrem.org/en/articles/compressed-contents-without-mod_deflate-en/ – Zydnar Jun 02 '19 at 17:07
  • No more need to register the subscriber into the config file (services.yaml) – Edouard May 02 '22 at 04:19