Compression

    To install the Compression feature, pass it to the install function in the application initialization code. This can be the main function …

    … or a specified module:

    1. import io.ktor.features.*
    2. // ...
    3. install(Compression)
    4. // ...
    5. }

    This enables the gzip, deflate, and identity encoders on a server. In the next chapter, we’ll see how to enable only specific encoders and configure conditions for compressing data.

    To enable only specific encoders, call the corresponding extension functions, for example:

    You can specify the priority for each compression algorithm by establishing the property:

    1. install(Compression) {
    2. gzip {
    3. priority = 0.9
    4. }
    5. deflate {
    6. priority = 1.0
    7. }

    In the example above, deflate has a higher priority value and takes precedence over gzip. Note that the server first looks at the values within the Accept-Encoding header and then takes into account the specified priorities.

    The Compression feature allows you to disable compression for responses whose size doesn’t exceed the specified value. To do this, pass the desired value (in bytes) to the function:

    1. install(Compression) {
    2. deflate {
    3. minimumSize(1024)
    4. }
    5. }

    If necessary, you can provide a custom condition using the condition function and compress data depending on the specific request parameters. The code snippet below shows how to compress requests for the specified URI:

    HTTPS with the enabled compression is vulnerable to the attack. You can use various ways to mitigate this attack. For example, you can disable compression whenever the referrer header indicates a cross-site request. In Ktor, this can be done by checking the referrer header value:

    1. install(Compression) {
    2. gzip {
    3. condition {
    4. request.headers[HttpHeaders.Referrer]?.startsWith("https://my.domain/") == true
    5. }