我已阅读 Bundle 文档 (FOS rest-bundle),但找不到有关压缩响应的任何信息,而且我无法将压缩设置为在网络服务器级别发生。
有没有办法让包返回一个 gzip(或 deflate)压缩响应?
我目前的想法是实现一个响应监听器,捕获它并压缩它,但我觉得可能有一个现有的方法。
编辑
我无法在 FOS Rest Bundle 中找到启用此功能的任何内容 - 很可能他们希望它在服务器级别完成。解决方案是创建一个事件订阅者:
public function getSubscribedEvents() {
return [KernelEvents::RESPONSE => ['compressResponse', -256]];
}
在我的压缩响应方法中,我对正文内容使用 deflate 并添加适当的内容编码 header :
public function compressResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
if ($response->headers->get('content-type') !== 'application/json') {
return;
}
$response->setContent(gzdeflate($response->getContent()));
$response->headers->set('Content-encoding', 'deflate');
}
这很好地服务于我们的目的。
最佳答案
我们在 Apache 级别上实现了这一点,以便通过使用以下配置为 application/json 输出启用网络服务器压缩。
复制自standard deflate conf in PHP buildpack并覆盖它:
<IfModule filter_module>
<IfModule deflate_module>
AddOutputFilterByType DEFLATE application/json text/html text/plain text/xml text/css text/javascript application/javascript
</IfModule>
</IfModule>
将 application/json 添加到这个 conf 中对我们有用。
关于symfony - FOS 休息包 : Can the response be gzipped?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52561381/