"Expires" in http header for static content? how-to - http

What is the best way to add "Expires" in http header for static content? eg. images, css, js
The web server is IIS 6.0; the language is classical ASP

You could try something like this:
#ECHO OFF
REM ---------------------------------------------------------------------------
REM Caching - sets the caching on static files in a web site
REM syntax
REM Caching.CMD 1 d:\sites\MySite\WWWRoot\*.CSS
REM
REM %1 is the WebSite ID
REM %2 is the path & Wildcard - for example, d:\sites\MySite\WWWRoot\*.CSS
REM _adsutil is the path to ADSUtil.VBS
REM ---------------------------------------------------------------------------
SETLOCAL
SET _adsutil=D:\Apps\Scripts\adsutil.vbs
FOR %%i IN (%2) DO (
ECHO Setting Caching on %%~ni%%~xi
CSCRIPT %_adsutil% CREATE W3SVC/%1/root/%%~ni%%~xi "IIsWebFile"
CSCRIPT %_adsutil% SET W3SVC/%1/root/%%~ni%%~xi/HttpExpires "D, 0x69780"
ECHO.
)
Which sets the caching value for each CSS file in a web root to 5 days, then run it like this:
Caching.CMD 1 \site\wwwroot\*.css
Caching.CMD 1 \site\wwwroot\*.js
Caching.CMD 1 \site\wwwroot\*.html
Caching.CMD 1 \site\wwwroot\*.htm
Caching.CMD 1 \site\wwwroot\*.gif
Caching.CMD 1 \site\wwwroot\*.jpg
Kind of painful, but workable.
BTW - to get the value for HttpExpires, set the value in the GUI, then run
AdsUtil.vbs ENUM W3SVC/1/root/File.txt
to get the actual value you need

I think this is what you're after, It's Content Expiration under HTTP Headers in IIS Manager. I use the pattern of sticking static content under a folder like ~/Resources and setting the expiration on that particular folder to have a much longer life than the rest of the application.
Here's a link to the full article: IIS 6.0 F1: Web Site Properties - HTTP Headers Tab

For others coming from google: this will not work in iis6 but works in 7 and above.
In your web.config:
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>

in IIS admin you can set it for each file type or you can (for dynamic ones like aspx) do it in the code. After you have it setup you need to check the headers that are output with a tool like Mozilla firefox + live headers plugin - or you can use a web based tool like http://www.httpviewer.net/

I don't know if this is what you are looking for, but it does keep my pages from being cached.
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-store">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
<META HTTP-EQUIV="Cache-Control" CONTENT="max-age=0">
I got these from an article on line that I no longer have a reference for.

Terrible solution, the first command to create with adsutil will fail with error -2147024713 (0x800700B7) since the files your trying to create already exists.
Thanks.

Related

Set file's html reponse headers cache-control on IIS via powershell

I'm trying to set cache-control: max-age on the http response header on IIS to a specific file. I'm trying to do that using a PowerShell script or a CMD command. can I do that? if yes, how?
Too late to answer this question, might be helpful for those who are still looking for the solution.
I used "appcmd.exe" in Powershell.
Below is how I used in Powershell:
# path to appcmd.exe
$appCmd = "C:\windows\system32\inetsrv\appcmd.exe"
# Path to the folder where we want to set the cache max-age
# in this case its a "scripts" folder in "Default Web Site" site
$env:folderPathScripts = "Default Web Site/scripts"
# sets the max age to 2 days
& $appCmd --% set config "%folderPathScripts%" -section:staticContent -clientCache.cacheControlMode:UseMaxAge -clientCache.cacheControlMaxAge:2.00:00:00
or
#To disable the cache
& $appCmd --% set config "%folderPathScripts%" -section:staticContent -clientCache.cacheControlMode:DisableCache
I referred following links:
https://forums.iis.net/t/1174801.aspx?How+to+Remove+and+Add+custom+headers+convert+from+appcmd
https://technet.microsoft.com/en-us/library/jj635852(v=ws.11).aspx
https://technet.microsoft.com/en-us/library/cc770661(v=ws.10).aspx

Open Graph and internationalization - alway's in english

This is my first web site and i manage to make everything work except that.
I use ASP.Net and "Resources" files and then set the CurrentCulture which work's fine.
Now I want to share page of my website on Facebook. So i did use Open Graph tags.
I did try many combination of tags and i did try to rescrape in the Facebook Debugger but without succes. The retrieve description and title are ALWAY'S IN ENGLISH.
<meta property="og:locale:alternate" content="en_US" />
<meta property="og:locale:alternate" content="fr_FR" />
I also try to add:
<meta property="og:locale" content="fr_FR" />
Without success. I installed curl and run a "refresh" of facebook cache... still without success.
curl -X POST -F "id=http://facteurhumain.ca/facteur/lesNouvelles" -F "scrape=true" -F locale="fr_fr" "https://graph.facebook.com" -s
I did also try to put "en_US" and "fr_FR" in lower caps ("en_us", "fr_fr") without any changes.
Any pist of solution?
Thanks!!

How to Ensure Latest Javascript & CSS in Browser Cache in ASP.NET MVC

I would like to ensure that latest version of js & css are in client browser cache. I have followed this link (http://blog.robvolk.com/2009/04/ensure-latest-javascript-css-in-browser.html?showComment=1354714427404#c5850523542624593865)
The problem I am not getting new hash-code on every build. I even try to clean and rebuild it does have the same hash-code.
I would appreciate if someone could advise how can I handle the browser cache.
Thanks
I would suggest using bundling and minification of scripts and stylesheets. It is a new feature introduced together with MVC 4, but it seems, that someone was able to make it work with even MVC3 - ASP.NET MVC4 bundling in ASP.NET MVC3
ASP.NET Optimization uses similar approach as your solution - it appends a hash to the URL of script/style, but this hash is based on the content of the js/css file, not on an instance of the application assembly.
note: the blogpost by Jef Claes uses Microsoft.Web.Optimization package, that was replaced by Microsoft.AspNet.Web.Optimization, but I believe, it will work even with the Microsoft.AspNet.Web.Optimization package.
UPDATE: The previous version did not work on Azure, I have simplified and corrected below. (Note, for this to work in development mode with IIS Express, you will need to install URL Rewrite 2.0 from Microsoft http://www.iis.net/downloads/microsoft/url-rewrite - it uses the WebPi installer, make sure to close Visual Studio first)
I fought with it for a couple of days and ended up rolling my own. (see link below for full explanation) You basically Auto-increment the assembly version every time the project is built, and use that number for a routed static file on the specific resources you would like to keep refreshed. (so something.js is included as something.v1234.js with 1234 automatically changing every time the project is built) - I also added some additional functionality to ensure that .min.js files are used in production and regular.js files are used when debugging (I am using WebGrease to automate the minify process) One nice thing about this solution is that it works in local / dev mode as well as production. (I am using Visual Studio 2015 / Net 4.6, but I believe this will work in earlier versions as well.
To implement, you can follow the following steps: (I know this is an old post, but I ran across it while developing a solution):
How to do it: Auto-increment the assembly version every time the project is built, and use that number for a routed static file on the specific resources you would like to keep refreshed. (so something.js is included as something.v1234.js with 1234 automatically changing every time the project is built) - I also added some additional functionality to ensure that .min.js files are used in production and regular.js files are used when debugging (I am using WebGrease to automate the minify process) One nice thing about this solution is that it works in local / dev mode as well as production. (I am using Visual Studio 2015 / Net 4.6, but I believe this will work in earlier versions as well.
Step 1: Enable auto-increment on the assembly when built
In the AssemblyInfo.cs file (found under the "properties" section of your project change the following lines:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
to
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
Step 2: Set up url rewrite in web.config for files with embedded version slugs (see step 3)
In web.config (the main one for the project) add the following rules in the <system.webServer> section I put it directly after the </httpProtocol> end tag.
<rewrite>
<rules>
<rule name="static-autoversion">
<match url="^(.*)([.]v[0-9]+)([.](js|css))$" />
<action type="Rewrite" url="{R:1}{R:3}" />
</rule>
<rule name="static-autoversion-min">
<match url="^(.*)([.]v[0-9]+)([.]min[.](js|css))$" />
<action type="Rewrite" url="{R:1}{R:3}" />
</rule>
</rules>
</rewrite>
Step 3: Setup Application Variables to read your current assembly version and create version slugs in your js and css files.
in Global.asax.cs (found in the root of the project) add the following code to protected void Application_Start() (after the Register lines)
// setup application variables to write versions in razor (including .min extension when not debugging)
string addMin = ".min";
if (System.Diagnostics.Debugger.IsAttached) { addMin = ""; } // don't use minified files when executing locally
Application["JSVer"] = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString().Replace('.','0') + addMin + ".js";
Application["CSSVer"] = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString().Replace('.', '0') + addMin + ".css";
Step 4: Change src links in Razor views using the application variables we set up in Global.asax.cs
#HttpContext.Current.Application["CSSVer"]
#HttpContext.Current.Application["JSVer"]
For example, in my _Layout.cshtml, in my head section, I have the following block of code for stylesheets:
<!-- Load all stylesheets -->
<link rel='stylesheet' href='https://fontastic.s3.amazonaws.com/8NNKTYdfdJLQS3D4kHqhLT/icons.css' />
<link rel='stylesheet' href='/Content/css/main-small.#HttpContext.Current.Application["CSSVer"]' />
<link rel='stylesheet' media='(min-width: 700px)' href='/Content/css/medium.#HttpContext.Current.Application["CSSVer"]' />
<link rel='stylesheet' media='(min-width: 700px)' href='/Content/css/large.#HttpContext.Current.Application["CSSVer"]' />
#RenderSection("PageCSS", required: false)
A couple things to notice here: 1) there is no extension on the file. 2) there is no .min either. Both of these are handled by the code in Global.asax.cs
Likewise, (also in _Layout.cs) in my javascript section: I have the following code:
<script src="~/Scripts/all3bnd100.min.js" type="text/javascript"></script>
<script src="~/Scripts/ui.#HttpContext.Current.Application["JSVer"]" type="text/javascript"></script>
#RenderSection("scripts", required: false)
The first file is a bundle of all my 3rd party libraries I've created manually with WebGrease. If I add or change any of the files in the bundle (which is rare) then I manually rename the file to all3bnd101.min.js, all3bnd102.min.js, etc... This file does not match the rewrite handler, so will remain cached on the client browser until you manually re-bundle / change the name.
The second file is ui.js (which will be written as ui.v12345123.js or ui.v12345123.min.js depending on if you are running in debug mode or not) This will be handled / rewritten. (you can set a breakpoint in Application_OnBeginRequest of Global.asax.cs to watch it work)
Full discussion on this at: Simplified Auto-Versioning of Javascript / CSS in ASP.NET MVC 5 to stop caching issues (works in Azure and Locally) With or Without URL Rewrite (including a way do it WITHOUT URL Rewrite)

Resource interpreted as Script but transferred with MIME type text/x-c++

LESS beginner.
Wrote a test html below
<head>
<link rel="stylesheet" type="text/css" href="404.less">
<script src="http://lesscss.googlecode.com/files/less-1.3.0.min.js" type="text/javascript"></script>
</head>
<body>test</body>
But got a warning in Chrome
Resource interpreted as Script but transferred with MIME type text/x-c++: "http://lesscss.googlecode.com/files/less-1.3.0.min.js".
Why?
You probably want your link tag to say:
<link rel="stylesheet/less" type="text/css" href="404.less">
That said, if this is being served from a webserver it could be that that's detecting the mime type wrong from the file extension. If it's an apache server though, there's an easy fix. Add this to/create a .htaccess file in your webroot, containing the line:
AddType text/css less
I had a similar issue with twitter follow-me buttons when I was reviewing local html files in chrome. To fix this I just fired up web matrix 2.0 and pointed at my folder. Hope this helps.

Resource interpreted as stylesheet but transferred with MIME type text/html

This is my html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Language" content = "en"/>
<meta http-equiv = "Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="/xxx/app/www/style.css">
Now when I load the page, Safari's inspector gives me:
Resource interpreted as stylesheet but transferred with MIME type text/html
I'm working on localhost with MAMP. I'm not sure what to modify to get this to work. I read that this might be a server problem of some kind.
How do I solve it?
Create an .htaccess file into your root folder (or update the existing one) with this line inside
AddType text/css .css
this will tell apache to send the right content-type header for .css file
There is possibility that not just css resources were interpreted wrongly. It maybe a problem of your webserver configuration.
The best way to check is to go to Chrome -> Network tab and check responses section for each request.
Also you can run $ curl -I http://path_to_file_or_page with terminal and have a look at response, you should see it in following format, e.g. Content-Type: image/jpeg
So, if it will occur that webserver (apache) does it for all filesthen you can try to solve the problem in following way:
Check your /etc/apache2/apache2.conf
If there are any SetHandler application/x-httpd-php line, try to comment it and then reload your apache by $ sudo system apache2 reload
Let us know if the problem is still there.
It could be that your web server is properly configured but it really is returning HTML instead of CSS.
Check that you have the correct path, spelling, case, etc. Hit the URL directly and see what comes back. Your web server might be responding with an error page (HTML) and a 200-Ok instead of a 404-Not Found.
I'm not saying this ever happened to me...

Resources