Laravel: How to Compress Response with Gzip

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

In the modern web, performance is key to improving user experience and SEO rankings. One way to improve the loading time of your web application is by compressing your responses using Gzip. Laravel, as a robust PHP framework, provides several mechanisms to enable Gzip compression. In this tutorial, we will walk through the steps needed to set up Gzip compression in a Laravel application to improve its efficiency and speed.

What is Gzip Compression?

Gzip is a file format and a software application used for file compression and decompression. When applied to web applications, it compresses your website content before sending it over to the browser, which then decompresses the content before rendering it. This process reduces the size of the data transferred between your server and the client, leading to faster load times.

Enabling Gzip in Laravel

Basic Configuration

To start with Gzip compression in Laravel, we must ensure that our web server has mod_deflate or mod_gzip enabled. For Apache servers, you can enable mod_deflate by adding the following lines to your .htaccess file:

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

For Nginx servers, Gzip compression is enabled by default, but you can customize the settings in the nginx.conf file:

http {
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}

Middleware in Laravel

Another way to enable Gzip compression is by using middleware in Laravel. Middleware acts as a filter for HTTP requests and you can use it to compress your responses before they are sent to the client. Create a new middleware using the Artisan command:

php artisan make:middleware CompressResponse

Next, add the following code in the handle method of your newly created CompressResponse middleware:

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

    if (!$request->is('api/*')) {  // Avoid compressing API routes
        ob_start('ob_gzhandler');
    }

    return $response;
}

Don’t forget to register your middleware in the Kernel.php file by adding it to the $middleware array or the $routeMiddleware array if you want to apply it to specific routes only.

Testing The Gzip Compression

To test if Gzip compression is correctly working, you can use online tools like GTmetrix or Google PageSpeed Insights. These tools will give you information about the compression being applied to your responses and the performance improvement it achieves.

Advanced Gzip Configuration

Vary Header

Another best practice when using Gzip is to include the ‘Vary: Accept-Encoding’ header in your responses. This tells proxies to cache both the compressed and uncompressed versions of the content based on the ‘Accept-Encoding’ of the request. You can set this header in your Apache or Nginx configuration, or within your Laravel middleware:

$response->header('Vary', 'Accept-Encoding');

Conditionally Compressing Responses

In certain cases, such as when serving already compressed files like images or PDFs, Gzip compression is unnecessary. You may modify the middleware to exclude such routes or file types from compression:

if (!$request->is('images/*')) {  // skip compressing images
    ob_start('ob_gzhandler');
}

Conclusion

Using Gzip to compress your Laravel application’s responses can result in significant performance improvements. The bandwidth savings translate to faster loading times and better user experiences. By following the steps outlined in this tutorial and adapting the compression settings to your application’s specific needs, you have everything you need to start utilizing Gzip compression efficiently.