Support serving of pre-GZIP encoded files
Pre-GZIPping files is seemingly becoming more popular. This involves running a tool ahead of deployment that creates GZIPped copies of suitable files in the site, e.g. site.js => site.js.gzip. Then the file serving aspect of the web server will serve the GZIPped file when appropriate.
:thumbsup: for this one.
I'd also like to point out that this shouldn't be about "pre-gziping", but rather pre-compressing in general, no matter what the encoding format is.
For example, Microsoft and Google have both played with improved encoding schemes (peerdist and sdch). At one point Chrome even included sdch in its Accept-Encoding header. Of course these two examples are a bit crumby since neither caught on, but new compression techniques come up all the time.
What this means is, in reality, I might want to pre-compile a file into multiple formats and have the proper one selected based on the Accept-Encoding. My content directory could have several "gzip compatible" files encoded with zopfli (*.gz), the same files encoded in sdch (*.sdch) as well as the original uncompressed files for really old browsers.
I think of this as being very analogous to keeping images in both *.jpg and *.webp formats, and serving the appropriate ones at the appropriate times.
I found simple workaround based on URL redirect supported in HTTP:
class Startup
{
private StaticFileOptions StaticFileOptions
{
get
{
return new StaticFileOptions
{
OnPrepareResponse = OnPrepareResponse
};
}
}
private void OnPrepareResponse(StaticFileResponseContext context)
{
var file = context.File;
var request = context.Context.Request;
var response = context.Context.Response;
if (file.Name.EndsWith(".gz"))
{
response.Headers[HeaderNames.ContentEncoding] = "gzip";
return;
}
if (file.Name.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) != -1)
{
var requestPath = request.Path.Value;
var filePath = file.PhysicalPath;
if (IsDevelopment)
{
if (File.Exists(filePath.Replace(".min.", ".")))
{
response.StatusCode = (int)HttpStatusCode.TemporaryRedirect;
response.Headers[HeaderNames.Location] = requestPath.Replace(".min.", ".");
}
}
else
{
var acceptEncoding = (string)request.Headers[HeaderNames.AcceptEncoding];
if (acceptEncoding.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) != -1)
{
if (File.Exists(filePath + ".gz"))
{
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Headers[HeaderNames.Location] = requestPath + ".gz";
}
}
}
}
}
public void Configure(IApplicationBuilder application)
{
application
.UseDefaultFiles()
.UseStaticFiles(StaticFileOptions)
}
}
I used Wikipedia as reference. This approach also allows to use not minified files in development environment with no need to change links on client side.
I found that currect implementation of 'aspnet/StaticFiles' lacks of two feature:
- Declarative setup of 'Content-Encoding' header. I suppose it can be implemented very easy - by adding second dictionary to FileExtensionContentTypeProvider.
- Redirect support. Current design doesn't provide the ability to cancel invoke 'IHttpSendFileFeature.SendFileAsync/StreamCopyOperation.CopyToAsync'.
@davidfowl fyi.
In support of my comment above, both FireFox and Chrome will be shipping support for Brotli compression soon.
:+1:
Actually, even a good story for serving gzipped static files (with a cache, of course, since it's static compression) is currently lacking. I'm saying this in the "conventional", "IIS-kind" of way, as opposed to the build-time gzip generation. Or did I miss something?
For those coming here from Google with dynamic content compression needs, you might try this gist: https://gist.github.com/PinpointTownes/ac7059733afcf91ec319
Would it be beyond the scope of this to suggest that StaticFiles should optionally allow cached "on-demand" compression of files? (I.e. gzip on first request and put result to file system cache, serve gzip requests from there)
Really looking forward to being able to do this. I can go through all the trouble of bundling, minifying, tree shaking and gzipping to get things down to an absolute minimum size... but I can't serve those .js.gz files and it's problematic.
I'm also strugglin to get IIS to gzip itself as well, but that's for another area entirely.
https://github.com/aspnet/Home/issues/1584
https://github.com/AnderssonPeter/CompressedStaticFiles
With Angular (2) creating *.gz files when doing --prod builds, it would be great to have this out of the box.
Other related use cases are serving pre-brotli compressed (.br) files and also serving WebP (.webp) files instead of PNG/JPG/etc.
@JohannesRudolph you should now be able to combine ResponseCaching, ResponseCompression, and StaticFiles to achieve dynamic compression and caching of static files. @JunTaoLuo this would be a good combo to test.
Can folks clarify if they expect the original url to contain the compression extension (e.g. ".gz")? Some of the above samples do and some don't. I assume content negotiation based on accept headers would be the more general case.
Great! Content-negotiation is (from my experience) the far more often-used and preferred method.
On Fri, Feb 17, 2017 at 2:59 PM, Chris R [email protected] wrote:
Can folks clarify if they expect the original url to contain the compression extension (e.g. ".gz")? Some of the above samples do and some don't. I assume content negotiation based on accept headers would be the more general case.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/aspnet/StaticFiles/issues/7#issuecomment-280656573, or mute the thread https://github.com/notifications/unsubscribe-auth/AAH8NyZXuqJehp3rBf7VkFTq_XulZ8gYks5rdafHgaJpZM4CQ_LY .
@Tratcher -- I would not expect the original URL to contain the extension.
Also, looks like the Angular CLI will no longer output the "*.gz" files, so @Tratcher's ResponseCaching and ResponseCompression solution may be sufficient in that case?
@Tratcher do you have an example of combining those three bits of middleware to suit this scenario?
Thank you.
@JunTaoLuo can you do a sample?
A small example would be really appreciated here if possible. Thanks in advance.
You can take a look at the sample I have created at https://github.com/JunTaoLuo/MiddlewaresSample which uses ResponseCaching, ResponseCompression and StaticFiles to create, cache and serve different representations of the same resource.
Here's the sample output where I made 6 requests to http://localhost:5000/Foo.txt. The first was sent with no Accept-Encoding header, the second contained Accept-Encoding: gzip and the third had Accept-Encoding: custom. Then I made the first three requests again and checked that they were served from cache.
Hosting environment: Production
Content root path: C:\gh\tp\MiddlewaresSample\MiddlewaresSample\MiddlewaresSample
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/Foo.txt
info: Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware[24]
No cached response available for this request.
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/Foo.txt'. Physical path: 'C:\gh\tp\MiddlewaresSample\MiddlewaresSample\MiddlewaresSample\wwwroot\Foo.txt'
info: Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware[26]
The response has been cached.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 206.5195ms 200 text/plain
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/Foo.txt
info: Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware[24]
No cached response available for this request.
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/Foo.txt'. Physical path: 'C:\gh\tp\MiddlewaresSample\MiddlewaresSample\MiddlewaresSample\wwwroot\Foo.txt'
info: Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware[26]
The response has been cached.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 23.3728ms 200 text/plain
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/Foo.txt
info: Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware[24]
No cached response available for this request.
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/Foo.txt'. Physical path: 'C:\gh\tp\MiddlewaresSample\MiddlewaresSample\MiddlewaresSample\wwwroot\Foo.txt'
info: Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware[26]
The response has been cached.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 3.5304ms 200 text/plain
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/Foo.txt
info: Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware[22]
Serving response from cache.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 7.703ms 200 text/plain
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/Foo.txt
info: Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware[22]
Serving response from cache.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 1.4551ms 200 text/plain
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/Foo.txt
info: Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware[22]
Serving response from cache.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 1.3005ms 200 text/plain
Hmm, no logs for the compression middleware...
@muratg why was this closed?