Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

asp.net - Stopping cookies being set from a domain (aka "cookieless domain") to increase site performance

I was reading in Google's documentation about improving site speed. One of their recommendations is serving static content (images, css, js, etc.) from a "cookieless domain":

Static content, such as images, JS and CSS files, don't need to be accompanied by cookies, as there is no user interaction with these resources. You can decrease request latency by serving static resources from a domain that doesn't serve cookies.

Google then says that the best way to do this is to buy a new domain and set it to point to your current one:

To reserve a cookieless domain for serving static content, register a new domain name and configure your DNS database with a CNAME record that points the new domain to your existing domain A record. Configure your web server to serve static resources from the new domain, and do not allow any cookies to be set anywhere on this domain. In your web pages, reference the domain name in the URLs for the static resources.

This is pretty straight forward stuff, except for the bit where it says to "configure your web server to serve static resources from the new domain, and do not allow any cookies to be set anywhere on this domain". From what I've read, there's no setting in IIS that allows you to say "serve static resources", so how do I prevent ASP.NET from setting cookies on this new domain?

At present, even if I'm just requesting a .jpg from the new domain, it sets a cookie on my browser, even though our application's cookies are set to our old domain. For example, ASP.NET sets an ".ASPXANONYMOUS" cookie that (as far as I'm aware) we're not telling it to do.

Apologies if this is a real newb question, I'm new at this!

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is how I've done in my website:

  1. Setup a website on IIS with an ASP.NET application pool
  2. Set the binding host to your.domain.com
    • Note: you cannot use domain.com or else the sub-domain will not be cookieless
  3. Create a folder on the website called Static
  4. Setup another website, point it to Static folder created earlier.
  5. Set the binding host to static.domain.com
  6. Use an application pool with unmanaged code
  7. On the settings open Session State and check Not enabled.

Now you have a static website. To setup open the web.config file under Static folder and replace with this one:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.web>
    <sessionState mode="Off" />
    <pages enableSessionState="false" validateRequest="false" />
    <roleManager>
      <providers>
        <remove name="AspNetWindowsTokenRoleProvider" />
      </providers>
    </roleManager>
  </system.web>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
    </staticContent>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

This is going to cache the files for 30 days, remove a RoleManager (I don't know if it changes anything but I removed all I could find), and remove an item from Response Headers.

But here is a problem, your content will be cached even when a new version is deployed, so to avoid this I made an helper method for MVC. Basically you have to append some QueryString that will change every time you change these files.

default.css?v=1   ?v=2  ...

My MVC method gets the last write date and appends on the file url:

public static string GetContent(this UrlHelper url, string link)
{
    link = link.ToLower();

    // last write date ticks to hex
    var cacheBreaker = Convert.ToString(File.GetLastWriteTimeUtc(url.RequestContext.HttpContext.Request.MapPath(link)).Ticks, 16);

    // static folder is in the website folders, but instead of
    // www.domain.com/static/default.css I convert to
    // static.domain.com/default.css
    if (link.StartsWith("~/static", StringComparison.InvariantCultureIgnoreCase))
    {
        var host = url.RequestContext.HttpContext.Request.Url.Host;
        host = String.Format("static.{0}", host.Substring(host.IndexOf('.') + 1));

        link = String.Format("http://{0}/{1}", host, link.Substring(9));

        // returns the file URL in static domain
        return String.Format("{0}?v={1}", link, cacheBreaker);
    }

    // returns file url in normal domain
    return String.Format("{0}?v={1}", url.Content(link), cacheBreaker);
}

And to use it (MVC3 Razor):

<link href="@Url.GetContent("~/static/default.css")" rel="stylesheet" type="text/css" />

If you are using another kind of application you can do the same, make a method that to append HtmlLink on the page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...