Ctrl + K
Performance15 min read

HTTP Compression Best Practices

Understand HTTP compression, Brotli and gzip, compression levels, supported content types, caching considerations and practical ways to reduce web transfer sizes.

Published: 2026-09-02

HTTP compression reduces the amount of data a web server sends to a browser by encoding text-based responses into a smaller representation. Smaller responses require less bandwidth and usually arrive faster, which can improve page loading performance, especially on slower networks or when a page contains large JavaScript, CSS, HTML, SVG or JSON files.

Modern websites commonly use Brotli or gzip compression for HTTP responses. The best configuration depends on the response type, compression algorithm, server software, caching strategy and CPU resources available to the server. Compression is most useful when it reduces transfer size without introducing unnecessary processing overhead.

What Is HTTP Compression?

HTTP compression is a technique that reduces the size of an HTTP response before it is transferred over the network. The server compresses the response using an algorithm such as Brotli or gzip, and the browser decompresses it after receiving the data.

Browser
   ↓
Accept-Encoding: br, gzip
   ↓
Web Server
   ↓
Compress Response
   ↓
Content-Encoding: br
   ↓
Compressed Response
   ↓
Browser decompresses data

Compression does not normally change the logical content of a response. A compressed HTML document still represents the same HTML after decompression. The difference is that fewer bytes need to travel between the server and the client.

Why HTTP Compression Matters

Text-based web resources often contain repeated words, characters, property names and structural patterns. Compression algorithms can represent these repetitions more efficiently than sending the original data. This can significantly reduce network transfer size.

  • Reduce response transfer size.
  • Decrease bandwidth consumption.
  • Improve loading performance on slower connections.
  • Reduce the amount of data transferred from servers and CDNs.
  • Improve delivery of HTML, CSS, JavaScript, JSON and SVG resources.
  • Help large text responses arrive faster.

Brotli vs gzip

Brotli and gzip are the two most common compression algorithms encountered in modern web delivery. Both can compress HTTP responses, but Brotli was designed with modern web content and compression requirements in mind and often produces smaller files than gzip at comparable settings.

FeatureBrotligzip
Typical web usageModern web deliveryVery widely supported
Compression efficiencyUsually betterGood
Browser supportModern browsersExtremely broad
Static assetsExcellentExcellent
Dynamic responsesGood with appropriate settingsGood with appropriate settings
CompatibilityModern clientsVery high

For modern websites, Brotli is generally the preferred compression format when the client supports it. gzip remains an important fallback because it is broadly supported and still provides substantial compression for text-based resources.

How Content Negotiation Works

Browsers indicate which compression formats they understand using the Accept-Encoding request header. The server examines this information and selects an appropriate representation.

GET /app.js HTTP/1.1
Host: example.com
Accept-Encoding: br, gzip

If the server chooses Brotli, it can return the compressed response with the Content-Encoding header set to br. If Brotli is unavailable but gzip is supported, the server can return gzip instead.

HTTP/1.1 200 OK
Content-Type: application/javascript
Content-Encoding: br

The Vary Header and Compression

When a server can return different representations of the same resource depending on Accept-Encoding, caches need to know that the response varies according to that request header. The Vary header can communicate this requirement.

Vary: Accept-Encoding

This is particularly important when compressed responses are cached. Without correct cache variation, a cache could potentially serve an inappropriate representation to a client that did not request or support that encoding.

💡 When compressed and uncompressed representations can both be served, make sure your server or CDN handles Accept-Encoding variation correctly.

Which Content Types Should Be Compressed?

Compression is most effective for text-based formats because they usually contain substantial repetition. HTML, CSS, JavaScript, JSON, XML, SVG and plain text are common candidates.

Content TypeCompress?Reason
text/htmlYesText compresses very well
text/cssYesUsually highly compressible
text/javascriptYesLarge text-based source
application/javascriptYesText-based JavaScript
application/jsonYesHighly repetitive text structure
image/svg+xmlYesSVG is text-based
application/xmlYesText-based markup
text/plainYesText compresses efficiently

Which Files Usually Should Not Be Compressed Again?

Many binary formats are already compressed. Compressing them again often produces little benefit and consumes CPU resources. Common examples include JPEG images, PNG images, WebP images, AVIF images, MP4 videos, ZIP archives and compressed font formats.

FormatTypical Recommendation
JPEGDo not HTTP-compress again
PNGUsually do not HTTP-compress again
WebPUsually do not HTTP-compress again
AVIFUsually do not HTTP-compress again
MP4Do not HTTP-compress again
ZIPDo not HTTP-compress again
WOFF2Usually do not HTTP-compress again
⚠️ HTTP compression is not a replacement for optimizing images, videos or other binary assets. Recompressing already compressed formats can increase CPU usage while providing little or no reduction in transfer size.

Brotli Compression Levels

Brotli supports multiple compression quality levels. Higher levels can produce smaller output, but they generally require more CPU time. The optimal level therefore depends on whether the resource is generated dynamically or compressed once and served repeatedly.

Compression SettingTypical Trade-Off
LowFast compression, larger output
MediumBalanced CPU usage and size
HighSmaller output, higher CPU cost

For dynamic responses, extremely high compression settings are often unnecessary because the server may need to compress every response. For static files, higher compression levels can be more attractive because the compression work can be performed during the build or deployment process and the resulting file can then be reused.

gzip Compression Levels

gzip also provides compression levels that trade CPU usage for output size. Increasing the level does not always produce a meaningful reduction in file size, so choosing the maximum setting for every response is rarely the best approach.

A moderate compression level is often appropriate for dynamic content. Static assets can be compressed more aggressively ahead of time, especially when they are requested frequently and rarely change.

Static vs Dynamic Compression

One of the most important compression decisions is whether a resource is compressed dynamically when requested or precompressed before it is served. Dynamic compression is convenient because it can handle changing content, while static compression can reduce runtime CPU usage.

ApproachAdvantagesDisadvantages
Dynamic compressionWorks with changing responsesUses server CPU during requests
Precompressed assetsLow runtime CPU usageRequires build or deployment support
CDN compressionOffloads work from originDepends on CDN configuration

Compression and Caching

Compression should be considered together with HTTP caching. If a resource is cached for a long time, the cost of generating its compressed representation becomes less important because the same representation can be reused for many requests.

Static JavaScript and CSS files are especially suitable for this approach. A build system can generate optimized assets, a server or CDN can deliver compressed representations, and cache headers can allow clients and intermediary caches to reuse them.

Compression and Content-Encoding

The Content-Encoding response header tells the client which content coding was applied to the representation. For example, br indicates Brotli compression and gzip indicates gzip compression.

Content-Encoding: br

Content-Encoding should not be confused with Content-Type. Content-Type describes what the resource represents, such as text/html or application/json. Content-Encoding describes how that representation has been encoded for transfer.

HeaderPurpose
Content-TypeDescribes the media type
Content-EncodingDescribes the applied content coding
Accept-EncodingLists encodings accepted by the client
VaryDescribes request headers affecting representation

HTTP Compression and CDN Delivery

CDNs can perform compression close to users, reducing the amount of data transferred over the network and offloading work from the origin server. A CDN may store or generate compressed representations and select an appropriate encoding based on the requesting client's capabilities.

When using a CDN, avoid configuring compression independently at every layer without understanding how the layers interact. The origin server, CDN and browser should have a clear responsibility for compression and caching.

💡 If your CDN already performs Brotli or gzip compression, verify its behavior before enabling another compression layer at the origin. Double-compressing a response is unnecessary and can cause incorrect delivery.

Nginx Compression Example

Nginx can be configured to compress suitable response types. A basic gzip configuration can look like this:

gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types
    text/plain
    text/css
    text/xml
    application/json
    application/javascript
    application/xml
    image/svg+xml;

The exact configuration should be adapted to the application's requirements and the Nginx version. Modern deployments may also use Brotli through supported modules or infrastructure provided by a reverse proxy or CDN.

Apache Compression Example

Apache can use mod_deflate for gzip compression. A simplified configuration may look like this:

AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE image/svg+xml

Apache installations can also use additional modules or a reverse proxy for Brotli support. The correct configuration depends on the hosting environment and available modules.

Minimum Response Size

Very small responses may not benefit from compression because compression itself introduces metadata and processing overhead. Servers commonly use a minimum response size before applying compression.

There is no universal size threshold that is optimal for every website. The appropriate value depends on the compression algorithm, infrastructure and workload. The goal is to avoid spending CPU resources compressing responses that cannot achieve a meaningful reduction.

Compression and CPU Usage

Compression is a trade-off between network transfer size and computational work. Stronger compression can reduce bandwidth usage but may require additional CPU time. This matters particularly for high-traffic applications that generate responses dynamically.

GoalPreferred Strategy
Minimize CPU usageUse moderate compression
Minimize transfer sizeUse stronger compression where practical
Dynamic contentFavor balanced settings
Static assetsPrecompress when possible
High trafficConsider CDN or edge compression

Compression and Minification

Minification and HTTP compression solve related but different problems. Minification changes the source representation by removing unnecessary characters such as whitespace and comments. Compression encodes the resulting representation into a smaller transferable form.

Source JavaScript
      ↓
Minification
      ↓
Smaller JavaScript
      ↓
Brotli or gzip
      ↓
Smaller network transfer

Using both techniques is common for production websites. Minification reduces the amount of meaningful source data, while compression further reduces the number of bytes required to transmit that data.

Compression Is Not a Replacement for Code Splitting

A very large JavaScript bundle can still negatively affect performance even when it is highly compressed. Compression reduces network transfer size, but the browser may still need to download, decompress, parse and execute the resulting JavaScript.

For large applications, compression should therefore be combined with techniques such as code splitting, lazy loading, tree shaking and removal of unused dependencies.

Checking Whether Compression Is Enabled

You can inspect response headers in browser developer tools or with HTTP inspection utilities. Look for the Content-Encoding response header and compare the transferred size with the resource's decoded size when the browser exposes both values.

Content-Type: text/css
Content-Encoding: br
Vary: Accept-Encoding

If a large text-based resource is returned without Content-Encoding, investigate whether compression is disabled, whether the response is below the configured threshold, whether the resource is already encoded, or whether another layer such as a CDN controls compression.

Common HTTP Compression Mistakes

Compression problems are often caused by overly broad rules, unnecessary recompression or configurations that ignore how browsers, caches and CDNs negotiate content encodings.

  • Compressing already compressed binary files.
  • Using extremely high compression levels for dynamic responses.
  • Forgetting to handle Accept-Encoding correctly.
  • Ignoring Vary: Accept-Encoding when required by the caching setup.
  • Compressing tiny responses where the benefit is negligible.
  • Compressing the same response multiple times at different infrastructure layers.
  • Assuming compression alone fixes frontend performance problems.
  • Failing to test compressed responses after changing server configuration.

Best Practices

  • Prefer Brotli for modern web clients when available.
  • Keep gzip as a broadly compatible fallback.
  • Compress text-based resources such as HTML, CSS, JavaScript, JSON and SVG.
  • Avoid recompressing formats that are already compressed.
  • Use balanced compression levels for dynamically generated responses.
  • Precompress static assets when the deployment pipeline supports it.
  • Use CDN or edge compression when appropriate.
  • Configure caching and compression together.
  • Verify Content-Encoding and Vary headers.
  • Measure real transfer sizes instead of assuming compression is working.
💡 The best compression configuration is not necessarily the one that produces the smallest possible file. Optimize for the overall balance between transfer size, CPU usage, cacheability and response latency.

Compression Strategy by Resource Type

ResourceRecommended Approach
HTMLBrotli or gzip
CSSBrotli or gzip
JavaScriptBrotli or gzip
JSON API responsesBrotli or gzip
SVGBrotli or gzip
JPEGImage optimization instead
WebPImage optimization instead
AVIFImage optimization instead
MP4Video encoding instead
ZIPServe without additional HTTP compression

HTTP Compression and Security

Compression can have security implications in certain situations. Historically, attacks such as BREACH demonstrated that compressing responses containing secrets alongside attacker-controlled content can sometimes reveal information through differences in compressed sizes. This does not mean compression should be disabled everywhere, but sensitive response designs should be evaluated carefully.

⚠️ Do not treat HTTP compression as a purely performance-related setting when responses contain sensitive secrets and attacker-controlled input. Security-sensitive applications should evaluate compression-related side channels as part of their threat model.

How Compression Fits Into Web Performance

HTTP compression is one part of a broader web performance strategy. Reducing transfer size can improve the delivery of critical resources, but the total loading experience also depends on server response time, DNS resolution, TLS negotiation, caching, rendering, JavaScript execution and image optimization.

Fast DNS
   ↓
Fast connection
   ↓
Fast server response
   ↓
Compressed resources
   ↓
Efficient caching
   ↓
Fast browser parsing and rendering

For this reason, compression should be combined with caching, efficient asset delivery, code splitting, minification and appropriate resource prioritization rather than used as the only performance optimization.

Frequently Asked Questions

What is HTTP compression?

HTTP compression reduces the size of HTTP responses before they are transferred to clients. Common compression algorithms include Brotli and gzip.

Is Brotli better than gzip?

Brotli often provides better compression ratios for modern web content, while gzip has extremely broad compatibility. Using Brotli with gzip as a fallback is a common strategy.

Should JavaScript and CSS be compressed?

Yes. JavaScript and CSS are text-based resources that usually benefit significantly from Brotli or gzip compression.

Should images be compressed with Brotli or gzip?

Usually no. Formats such as JPEG, WebP and AVIF are already compressed. Image-specific optimization is generally more appropriate than applying HTTP compression again.

Does compression replace minification?

No. Minification removes unnecessary characters from source files, while HTTP compression encodes the resulting representation for smaller network transfer. They can be used together.

Does HTTP compression use server CPU?

Yes, dynamic compression requires CPU resources. Precompressing static assets or using CDN compression can reduce runtime CPU usage.

What does Content-Encoding: br mean?

It means the HTTP response representation has been compressed using Brotli and the client should decode it before using the content.

Why is Vary: Accept-Encoding important?

It tells caches that the response representation can differ depending on the client's Accept-Encoding header, helping caches store and serve the correct representation.

Helpful HTTP Tools

A Cache-Control Generator helps create cache directives for HTTP responses, an Nginx Config Generator assists with server configuration, an Apache Config Generator helps build Apache configuration snippets, an HTTP Header Viewer lets you inspect response and request headers, and a Content-Type Finder helps identify the appropriate MIME type for a resource.

Conclusion

HTTP compression is an important part of modern web performance optimization. Brotli and gzip can significantly reduce the transfer size of HTML, CSS, JavaScript, JSON, SVG and other text-based resources, helping browsers receive useful content with fewer bytes transferred over the network.

A good compression strategy balances transfer size, CPU usage, caching and compatibility. Prefer Brotli when appropriate, keep gzip available as a fallback, avoid recompressing already compressed files, use sensible compression levels and verify Content-Encoding and Vary behavior. Combined with minification, caching, code splitting, CDN delivery and optimized assets, HTTP compression can make websites faster and more efficient without unnecessary server overhead.

Found an issue?

Found an error, outdated information, or something missing from this article? Let me know through the Contact page.

Your feedback helps improve our articles and keep them accurate and useful.