Set Custom Response Header for Specific Files on IIS 7.5 and Apache2


In IIS you can enable Static and Dynamic Compression that provides almost everything for you. In this case, the IIS compress files itself and send proper headers.

But if you have pre-compressed files, e.g., done by Webpack, it does not send proper response headers and a web browser raises an error, e.g., “Unexpected character…”. The problem is that Content-Encoding: gzip response header is not sent by the IIS and the browser does not know that the response file should be decoded.


A solution is to update web.config for these files so the IIS will add a specific header for these files via the rewrite rule.

Example for IIS 7.5

In this example, IIS will add Content-Encoding: gzip header to every file with the .js.gz extension. See  outboundRules section.

<?xml version="1.0" encoding="UTF-8"?>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
<rule name="Set custom HTTP response header">
<match serverVariable="RESPONSE_Content_Encoding" pattern=".*" />
<add input="{REQUEST_URI}" pattern="\.js\.gz$" />
<action type="Rewrite" value="gzip"/>

Example for Apache2

The same for Apache2 server. See filesMatch section.

<VirtualHost *:5080 >

DocumentRoot /var/www/site

<Directory /var/www/site>
Require all granted
RewriteEngine on # Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L] # Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

<filesMatch "(\.js\.gz)$">
Header set Content-Encoding "gzip"
ErrorLog /var/log/apache2/site_error.log
CustomLog /var/log/apache2/site.log

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s