dev

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

Overview

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.

Solution

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"?>
<configuration>
<system.webServer>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
<rewrite>
<outboundRules>
<rule name="Set custom HTTP response header">
<match serverVariable="RESPONSE_Content_Encoding" pattern=".*" />
<conditions>
<add input="{REQUEST_URI}" pattern="\.js\.gz$" />
</conditions>
<action type="Rewrite" value="gzip"/>
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>

Example for Apache2

The same for Apache2 server. See filesMatch section.

<VirtualHost *:5080 >
ServerAdmin admin@exmaple.org
ServerName server.example.org

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]
</Directory>


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

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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