Configure the Apache server to make the browser accessible without caching

Source: Internet
Author: User
Tags html5 boilerplate

Original address:http://www.renfei.org/blog/http-caching.html

Each time you visit a webpage, the browser will usually download the required resources from the server, such as HTML documents, pictures, CSS, JavaScript, and even font files. Many of these files (examples) are rarely changed, if you have to re-download from the server every time, will unnecessarily increase the page loading time, but also to the server a certain amount of pressure. By reasonably configuring the cache policy, the browser can cache these static files in some way, and the next time the same resource is requested, the locally stored copy is used directly instead of being re-downloaded from the server.

Enabling caching has at least two points of obvious benefits:

    • Reduce page load times
    • Reduce server load

Whether the browser uses caching, how long it is cached, is controlled by the server. Accurately, when a browser requests a Web page (or other resource), some fields in the Response header section of the response sent back by the server indicate key information about the cache.

Cache-control

Cache-ControlThe HTTP response header is a new directive for the HTTP 1.1 protocol, and each resource can establish a cache policy by setting Cache-control. Typically, you can specify a maximum max-age time, in seconds, for a cache. For example, if set, it indicates that the Cache-Control: max-age=604800 resource has a valid time of 7 days. Once the browser obtains this resource for the first time, it will normally not communicate with the server for 7 days if it requests again, but instead uses the local copy directly.

In addition, you can specify public or mark for Cache-control private . If you use private, it means that the resource belongs only to the end user who made the request, which prevents the intermediary servers (such as proxy servers) from caching such resources. For files that contain user personal information, such as an HTML document that contains user names, you can set private, on the one hand, because these caches do not make sense to other users, and on the other hand, users may not want related files to be stored on untrusted servers. It should be noted that private does not make the cache more secure, it is also passed to the intermediary server (if the Web site for transport security requirements are high, you should use Transport Layer security measures). For public, all servers are allowed to cache the resource. Generally, it is reasonable for cache-control to be set to public for resources that everyone can access (such as the logo, pictures, scripts, etc.) of the website.

Expires

The same is used to control the cache, and the Expires response header from another angle-indicates the specific expiration date of the cache to control when the resource expires. Within the expiration time, if the request is initiated again, the browser will not normally communicate with the server, but instead use the local copy directly. The Apache server allows you to set the value of Expires in several ways, for example, based on the access time of the resource or the last modification time. Note that the time here is all used GMT (Greenwich Mean Time, GMT), not local.

When Expires and Cache-control appear simultaneously, the latter usually overrides the former setting. Since Expires is dependent on the user's system time, it is generally considered that the use of Cache-control is a better choice (basically all browsers support Cache-control directives).

Last-modified and ETag

The server can include fields or fields in the HTTP return header Last-Modified ETag . Last-modified represents the last modification time on the server side of the requested resource, and the ETag is a unique file identifier that generates a new etag each time the file is modified. The server notifies the browser of the version of the resource it obtains by sending the two fields to the browser.

Regardless of whether the cache is set through Cache-control or Expires, within the expiration time, when the user clicks the Browser refresh button, in order to ensure that the resources loaded by the user are up-to-date, most browsers will no longer directly use the data in the cache. Instead, a conditional request is issued (Conditional GET requests). For such requests, the browser contains or fields in the request If-Modified-Since header If-None-Match . The former is the last-modified the browser originally received, the latter being the ETag that the browser obtained. When the server discovers that the resource is updated later than the time provided by If-modified-since, or if the resource does not match the current ETag and If-none-match provided by the server, it responds to the entire resource, otherwise it responds to only one 304 not Modified Status code (so the browser will not need to re-download the entire resource). This mechanism can minimize the amount of data downloaded. In addition, if the cached resource has expired, the browser usually has two choices: re-download the resource, or issue a conditional request. Many browsers will take the latter to conserve resources.

Since the role of the last-modified and ETag is the same (both verifying that the resource is up-to-date with the server), only one is used. Last-modified is generally considered better (unlike Expires, which is generated by the server and does not depend on browser-side time).

Is my site enabled for caching? Use browser developer tools or plugins to view

To determine whether the cache is enabled, you only need to check the "response header" that is sent back by the server. Many browsers and tools can check this information, we use Firefox plugin Firebug as an example. :

Let's look at an example of a resource that does not have caching enabled:

No information is included Cache-Control as well Expires .

Online inspection

There are also handy online detection services to advise on website speed, which detects cache settings. For example, Yahoo! Company's YSlow, as well as Baidu Webmaster tools, have the corresponding function. We can go to the Baidu there to detect, currently do not need to log in to detect.

Set the long cache time for static resources using cached policies

Some resources are not changed for a long time, such as website logo images, jQuery libraries, fonts, etc., so they can be set to "never expire" cache time, for example, set to 10 years.

Make sure the file changes take effect

Sometimes we modify some resources, such as updating the jQuery version, or the CSS style of the website. If these resources are already cached, the user will not get a new version until the user refreshes the page manually, unless the cache is naturally expired. How do I force the browser to download again in this case? One of the most effective ways to do this is to include version information in the file name of such a resource and modify the file name accordingly after the change. When the browser discovers that the file has been replaced, it will not be able to use the cache and download again.

Carefully set expiration time for HTML documents

In most cases, requests for resources such as other images, CSS, JavaScript, and so on, come from a single HTML document. For this type of page, you should usually set a shorter expiration date, or simply do not set it. Because if such a page is cached, then information such as the file name of the resource contained in the page will be cached, causing the update to be difficult to ensure that the user immediately takes effect.

When referencing a static resource, do not use the Query String

Query string is ?key=val An example of a string, such as

<script src="/static/js/func.js?v=a87ff8"></script>

This prevents a subset of older browsers (including IE6) from caching the resource.

How to set the cache

For Apache servers, Expires an HTTP header or Cache-Control HTTP header instruction can be set via the Mod_expires module max-age . Edit the files in the appropriate directory .htaccess , or make changes directly to the Apache configuration file (depending on the version of the server system, may be httpd.conf or apache2.conf , etc.).

Sub-file Category settings

ExpiresByTypeYou can use the MIME Type of a file to set the expiration date for a class of files. For example:

<ifmodule mod_expires.c> ExpiresActive Span class= "K" >on expiresbytypetext/css  "Access plus 1 week"  Expiresbytypeapplication/javascript  "Access plus 2 weeks" expiresbytypeimage/ X-icon  "Access plus 6 months" expiresbytypeimage/gif  "Access plus 6 Months "expiresbytypeimage/png " Access plus 6 months " Expiresbytypeimage/jpeg  "Access plus 6 months" expiresbytypevideo/x-flv  "Access plus 6 months" expiresbytypeapplication/pdf  "Access plus 6 months" Span class= "NT" ></IFMODULE>            

This access plus 1 week means that the cache expiration is set to a week after the access time (that is, the current time). If access replaced, the modification cache expiration is set to one week after the file modification time. The time units you can use include:

    • Years
    • Months
    • Weeks
    • Days
    • Hours
    • Minutes
    • Seconds

Different times can also be combined, for example:

ExpiresByType text/html "access plus 1 month 15 days 2 hours"ExpiresByType image/gif "modification plus 5 hours 3 minutes"
Set according to the file name extension

You can use a mate regular expression if you want to specify a cache rule based on the extension FilesMatch . For brevity, I only prescribe it here ExpiresDefault . It has a low priority and will only take effect if the corresponding file does not have any other rules to match (including cache rules in the upper directory).

<IfModule mod_expires.c>    <FilesMatch "\.(css|js)$"> ExpiresActive on ExpiresDefault "access plus 1 week" </FilesMatch></IfModule>
For certain file settings

In the same vein, you can enable specific caching policies for some files. Note that the point () in the file name . needs to be escaped.

<IfModule mod_expires.c>    <FilesMatch "^(example\.css|example\.js)$"> ExpiresActive on ExpiresDefault "access plus 1 week" </FilesMatch></IfModule>
Set all the files in a folder

For static files, it is convenient to put them all in one directory and set all the files in that directory. However, you need to be careful here to prevent other rules from being ExpiresDefault overwritten.

<IfModule mod_expires.c>    ExpiresActive On ExpiresDefault "access plus 10 years"</IfModule>
Useful tools and references
    1. Cache-control Header Checker (detects if the given address is enabled Cache-control and teaches you how to set it)
    2. Caching Tutorial for Web Authors and webmasters
    3. HTTP Cache-Web Fundamentals (from Google developers)
    4. Baidu Webmaster Tools-Page Optimization recommendations
    5. H5bp/server-configs (HTML5 boilerplate provides a sample configuration file for all the most popular servers)

(GO) Configure Apache server to allow browser access without caching

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.