Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

asp.net - IIS 7.5 gzip compression at shared hosting

I have a web-site, which uses ASP.NET and is hosted at IIS 7.5 shared hosting, so I have no direct access to IIS settings. Now I want to enable gzip compression of my pages and css/js files using IIS capabilities, but none of recipes found at the Internet worked for me. For example, when I add what is written here to my Web.config, nothing changes: no errors, no compression.

Is this possible? If not, what's the best alternative?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I encountered the same problem, and so used .net's compression invoked using global.asax along-with renaming static css with .aspx extension and using url rewrite through Web.config Atop the .css.aspx I simply added

<%@ Page ContentType="text/css" %>

In rules of rewrite of system.webserver of configuration of Web.config:

<rule name="san aspx">
    <match url=".*[^/]$" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        </conditions>
    <action type="Rewrite" url="{R:0}.aspx" />
</rule>
<rule name="revert aspx">
    <match url="(.*).aspx$"/>
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        </conditions>
    <action type="Rewrite" url="{R:1}" />
</rule>

In Application_PreRequestHandlerExecute of global.asax

HttpApplication app = sender as HttpApplication;
string acceptEncoding = app.Request.Headers["Accept-Encoding"];
Stream prevUncompressedStream = app.Response.Filter;
if (acceptEncoding != null && acceptEncoding.Length > 0) {
    acceptEncoding = acceptEncoding.ToLower();
    if (acceptEncoding.Contains("gzip")){
        app.Response.Filter = new GZipStream(prevUncompressedStream, CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "gzip");
    }
}    
Response.Cache.VaryByHeaders["Accept-Encoding"] = true;

It appears intimidating, but done with building proper understanding, it works like charm and is worth the savings on SEO related with PageSpeed as well as shared hosting. I did try with my hosting provider's support, but they just marketed more exotic hosting packages instead. For compulsorily compressed content like .svgz file, I've used separate folder and httpProtocol of system.webserver of that folder's web.config I wrote:

<customHeaders>
    <add name="Content-Encoding" value="gzip" />
</customHeaders>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...