Using URL Rewrite in ASP.Net to improve your site's performance

To improve the performance of our site GillSoft.ie, we took help of Google "PageSpeed Insights" and among other things (like compression of JavaScript / CSS) it reported that some static file (like images / js / css) needed some extra care. The report created by "PageSpeed Insights" suggested that the HTTP response headers for these files did not have any cache control related information for the browser. So client-side caching was not being used properly.

The following text shows the HTTP response coming back for an image fetched from Gillsoft.ie by the browser.

Response HTTP/1.1 200 OK
Content-Type image/png
Last-Modified Mon, 07 Jul 2014 23:21:14 GMT
Accept-Ranges bytes
ETag "959442253a9acf1:0"
Server Microsoft-IIS/7.5
X-Powered-By ASP.NET
X-App-Hosting pool=classic
Date Mon, 14 Jul 2014 09:40:49 GMT
Content-Length 71313

With the URL Rewrite module in IIS, adding more information to the response headers can be easily achieved. We edited the web.config file and added "outboundRules" and the "rule" to add cache related information.

<rewrite>
<outboundRules>
<rule name="Set Cache-Control - Max Age">
<match serverVariable="RESPONSE_Cache_Control" pattern=".*" />
<conditions>
<add input="{REQUEST_URI}" pattern="\.(png|jpg|js|css|gif)$" />
</conditions>
<action type="Rewrite" value="public, must-revalidate, max-age=31536000"/>
</rule>
</outboundRules>
.....
</rewrite>

In the above example, we add the cache related information to the HTTP response header going back to the browser. Note the pattern for the file names on which this action should be performed. you may choose to change this pattern to suit your requirements. After making the changes, the HTTP response header for the same image were as shown below:

Response HTTP/1.1 200 OK
Cache-Control public, must-revalidate, max-age=31536000
Content-Type image/png
Last-Modified Mon, 07 Jul 2014 23:21:14 GMT
Accept-Ranges bytes
ETag "959442253a9acf1:0"
Server Microsoft-IIS/7.5
X-Powered-By ASP.NET
X-App-Hosting pool=classic
Date Mon, 14 Jul 2014 09:56:56 GMT
Content-Length 71313

Notice the presence of Cache-Control? This is what tells the client (browser) to cache some files so that they are not fetched each and every time. There a lot of resources on "Cache-Control" on the net and you may modify the response to suit your needs.

This led to a jump of 20 points (due to usage of browser side caching) in the Google PageSpeed Insights tool!

Not only the improvement in the Google Pagespeed Insights, we noticed fewer HTTP requests generated for pages (by watching network traffic in Firebug in Firefox).

Post your comments to let us know if this tip helps you in anyway or to share your ideas on this topic.

Add new comment