Documentation

You are viewing the documentation for the 2.5.8 release in the 2.5.x series of releases. The latest stable release series is 3.0.x.

§Configuring gzip encoding

Play provides a gzip filter that can be used to gzip responses.

§Enabling the gzip filter

To enable the gzip filter, add the Play filters project to your libraryDependencies in build.sbt:

libraryDependencies += filters

Now add the gzip filter to your filters, which is typically done by creating a Filters class in the root of your project:

Scala
import javax.inject.Inject

import play.api.http.DefaultHttpFilters
import play.filters.gzip.GzipFilter

class Filters @Inject() (gzipFilter: GzipFilter)
  extends DefaultHttpFilters(gzipFilter)
Java
import play.mvc.EssentialFilter;
import play.filters.gzip.GzipFilter;
import play.http.HttpFilters;

import javax.inject.Inject;

public class Filters implements HttpFilters {

    private EssentialFilter[] filters;

    @Inject
    public Filters(GzipFilter gzipFilter) {
        filters = new EssentialFilter[] { gzipFilter.asJava() };
    }

    public EssentialFilter[] filters() {
        return filters;
    }
}

The Filters class can either be in the root package, or if it has another name or is in another package, needs to be configured using play.http.filters in application.conf:

play.http.filters = "filters.MyFilters"

§Configuring the gzip filter

The gzip filter supports a small number of tuning configuration options, which can be configured from application.conf. To see the available configuration options, see the Play filters reference.conf.

§Controlling which responses are gzipped

To control which responses are and aren’t implemented, use the shouldGzip parameter, which accepts a function of a request header and a response header to a boolean.

For example, the code below only gzips HTML responses:

Scala
new GzipFilter(shouldGzip = (request, response) =>
  response.body.contentType.exists(_.startsWith("text/html")))
Java
GzipFilter gzipFilter = new GzipFilter(
  new GzipFilterConfig().withShouldGzip((req, res) ->
    res.body().contentType().orElse("").startsWith("text/html")
  ), materializer
);

Next: Configuring security headers