简体   繁体   中英

How to enable gzip compression on API Gateway?

I am having a bit of a trouble enabling gzip compression on API Gateway. I am using Laravel Vapor, which uses AWS Lambda under the hood.

I have scoured the API Gateway console dashboard for the settings, but to no avail. I have CORS setup in my application and I have the following enabled:

'allowedHeaders' => [
        'Accept',
        'Accept-Encoding',
        'Authorization',
        'Access-Control-Expose-Headers',
        'Content-Type',
        'X-Requested-With',
        'Origin',
        'X-Shadow-Progress',
        'X-Socket-ID',
        'x-socket-id'
    ],

I was under the impression that setting Accept-Encoding in my backend would do the trick, but it simply doesn't work. Response headers never have Content-Encoding: gzip in them.

I run a number of projects on Vapor. I forget if we had to do anything special inside of API gateway to get this going, but I created a piece of middleware that gzips responses which does the trick for us:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class GzipEncodeResponse
{
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if (in_array('gzip', $request->getEncodings()) && function_exists('gzencode')) {
            $response->setContent(gzencode($response->getContent(), 9));
            $response->headers->add([
                'Content-Encoding' => 'gzip',
                'X-Vapor-Base64-Encode' => 'True',
            ]);
        }
        return $response;
    }
}

This checks that the request accepts gzip encoding and if so, gzips the response and adds some necessary headers to get this to work.

Update; Since writing this answer, I've realised that there isn't a much content on Google explaining how to do this. I've detailed this approach and a little more about what's going on in a blog post on my website .

AWS API Gateway does support compression ( gzip and deflate ). It is just a bit hard to find. You can enable it either through the gateways settings in the AWS console or the AWS CLI.

In the AWS Console select your API Gateway and then you can find it under Settings > Content Encoding (see image below).

如何在 AWS 控制台中启用压缩

Documentation: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-enable-compression.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM