Installation
composer require erlandmuchasaj/laravel-gzip
Publish the config file (if needed):
php artisan vendor:publish --provider="ErlandMuchasaj\LaravelGzip\GzipServiceProvider"
Enable Gzip
Add the middleware to your app/Http/Kernel.php:
protected $middleware = [
// ...
\ErlandMuchasaj\LaravelGzip\Middleware\Gzip::class,
];
First Use Case
Content-Encoding: gzip header in the response.Global vs. Route-Specific
Route::middleware(Gzip::class)->group(function () {
// Routes where Gzip is enforced
});
Excluding Routes
Configure exclusions in config/gzip.php:
'excluded_routes' => [
'admin/*',
'api/v1/uncompressed',
],
Conditional Gzip by Request Override logic in a custom middleware:
public function handle($request, Closure $next)
{
if ($request->header('X-No-Gzip')) {
return $next($request);
}
return app(Gzip::class)->compress($next($request));
}
Content-Type Awareness
The package auto-detects text-based responses (e.g., text/html, application/json). For custom types, extend:
'compressible_content_types' => [
'text/html',
'application/json',
'application/xml',
// Add custom MIME types here
],
Response::cache()). Ensure cached responses are still compressed by placing the middleware after caching middleware in Kernel.php.Double Compression
Content-Encoding headers upstream or use:
'skip_if_already_compressed' => true, // in config/gzip.php
Non-Text Responses
'excluded_content_types' => [
'image/*',
'application/pdf',
],
Caching Headers Conflict
Cache-Control or ETag headers if not handled carefully.Kernel.php.Verify Compression Check headers with:
curl -I http://your-site.com
Look for:
Content-Encoding: gzip
Log Compression Stats
Enable debug mode in config/gzip.php:
'debug' => env('GZIP_DEBUG', false),
Logs will appear in storage/logs/laravel.log.
Custom Compression Levels
Override the default level (e.g., 9 for max compression) in a service provider:
$this->app->singleton(Gzip::class, function () {
return new \ErlandMuchasaj\LaravelGzip\Gzip(9); // Custom level
});
Pre/Post-Processing
Extend the Gzip class to modify responses:
class CustomGzip extends \ErlandMuchasaj\LaravelGzip\Gzip
{
public function compress($response)
{
$response = parent::compress($response);
// Add custom logic (e.g., modify headers)
return $response;
}
}
Browser-Specific Rules
Use middleware to conditionally apply Gzip based on User-Agent:
if (str_contains($request->userAgent(), 'Mobile')) {
return app(Gzip::class)->compress($next($request));
}
How can I help you explore Laravel packages today?