Skip to content

Commit 173e108

Browse files
authored
Merge pull request #2009 from brefphp/document-compression
Document HTTP responses compression
2 parents f6446aa + 3e777fa commit 173e108

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

docs/use-cases/websites.mdx

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,3 +211,40 @@ The last step will be to point your domain name DNS records to the CloudFront do
211211
- if you use another registrar and you want to point your root domain (without `www.`) to CloudFront, you will need to use a registrar that supports this (for example [CloudFlare allows this with a technique called CNAME flattening](https://support.cloudflare.com/hc/en-us/articles/200169056-Understand-and-configure-CNAME-Flattening))
212212

213213
Lift supports more advanced use cases like multiple domains, root domain to `www` redirects, and more. Check out [the Lift documentation](https://github.com/getlift/lift/blob/master/docs/server-side-website.md).
214+
215+
## Compressing HTTP responses
216+
217+
By default, Lift enables gzip and brotli compression for static assets served from S3. That means that if a client supports compressed responses (via the `Accept-Encoding` header), [CloudFront will cache and serve a compressed version of the asset](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html#compressed-content-cloudfront-how-it-works), which is usually smaller and faster to transfer.
218+
219+
However, dynamic responses generated by PHP (for example HTML pages) are not compressed. The reason is that CloudFront's cache is disabled for requests to PHP (Lift sets up the [`CachingDisabled` policy](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-cache-policies.html#managed-cache-policy-caching-disabled)), and therefore CloudFront does not compress non-cached responses.
220+
221+
You can compress PHP responses by using an HTTP middleware that compresses the response body and sets the `Content-Encoding` header. Here is an example for Laravel:
222+
223+
```php filename="app/Http/Middleware/CompressResponse.php"
224+
class CompressResponse
225+
{
226+
public function handle(Request $request, Closure $next)
227+
{
228+
/** @var \Illuminate\Http\JsonResponse $response */
229+
$response = $next($request);
230+
231+
if (! in_array('gzip', $request->getEncodings())) {
232+
return $response;
233+
}
234+
if ($response->headers->has('Content-Encoding')) {
235+
return $response;
236+
}
237+
238+
$content = $response->getContent();
239+
if (! $content) {
240+
return $response;
241+
}
242+
243+
$response->setContent(gzencode($content, 9));
244+
$response->headers->set('Content-Encoding', 'gzip');
245+
$response->headers->set('Content-Length', (string) strlen($content));
246+
247+
return $response;
248+
}
249+
}
250+
```

0 commit comments

Comments
 (0)