Detailed tutorial on configuring browser cache for static files in Apache/Nginx

Source: Internet
Author: User
Tags current time local time regular expression browser cache jquery library

The most obvious advantage of using cache for web pages is that it reduces page loading time and server load.

Whether the browser uses the cache or how long it takes to cache is controlled by the server. When a browser requests a webpage (or other resources), some fields in the response header returned by the server indicate the key information about the cache.

Cache-Control

The Cache-ControlHTTP response header is a new command added to the HTTP 1.1 protocol. You can set Cache-Control for each resource to create a Cache policy. Generally, you can specify a max-age for it, indicating the maximum cache time, in seconds. For example, if Cache-Control: max-age = 604800 is set, the validity period of the resource is 7 days. After the browser obtains the resource for the first time, if it requests the resource again within seven days, it usually does not communicate with the server, but directly uses the local copy.

You can also specify public or private tags for Cache-Control. If private is used, it indicates that the resource belongs only to the end user who sends the request. This will prohibit intermediate servers (such as proxy servers) from caching such resources. Private can be set for files containing users' personal information (such as an HTML document containing user names). On the one hand, these caches do not make any sense to other users, on the other hand, users may not want the related files to be stored on untrusted servers. It should be noted that private does not make the cache more secure, and it will also be transmitted to the intermediate server (if the website has high transmission security requirements, transport layer security measures should be used ). For public, all servers are allowed to cache the resource. Generally, it is reasonable to set Cache-Control to public for resources that can be accessed by all users (such as website logos, images, and scripts.

Expires

It is also used to control the cache. The Expires response header specifies the specific expiration date of the cache from another perspective to control when the resource Expires. If a request is initiated again within the Expiration Time, the browser usually does not communicate with the server, but directly uses the local copy. The Apache server allows you to set the Expires value in multiple ways, such as the resource access time or the last modification time. Note that the Time here uses Greenwich Mean Time (GMT) instead of the local Time.

When both Expires and Cache-Control appear, the latter usually overwrites the former setting. Because Expires depends on the user's system time, it is generally considered that using Cache-Control is a better choice (basically all browsers support the Cache-Control Command ).

Last-Modified and ETag

The server can include the Last-Modified field or ETag field in the HTTP response header. Last-Modified indicates the Last modification time of the requested resource on the server, and ETag is a unique file identifier. After each modification, a new ETag is generated. The server sends these two fields to the browser to notify the browser of the version of the resource it obtained.

Whether Cache-Control or Expires is used to set the Cache, when the user clicks the refresh button within the Expiration Time, to ensure that the resources loaded by the user are up-to-date, most browsers do not directly use the cached data, but send a Conditional Request ). For such requests, the browser will include the If-Modified-Since or If-None-Match field in the request header. The former is the Last-Modified obtained by the browser; the latter is the ETag obtained by the browser. When the server finds that the resource update time is later than the time provided by If-Modified-Since, or the current ETag of the resource on the server does not Match the time provided by If-None-Match, will respond to the entire resource; otherwise, only one 304 Not Modified status code will be returned (so the browser does Not need to download the entire resource again ). This mechanism can minimize data downloads. In addition, if the cached resource has expired, the browser usually has two options: re-download the resource or issue a conditional request. Many browsers adopt the latter to save resources.

Because the Last-Modified and ETag functions the same (both verify the latest resources to the server), you can use only one. It is generally considered that Last-Modified is better (unlike Expires, which is generated by the server and does not depend on the browser end time ).


Does my website enable cache?

View with browser developer tools or plug-ins

To determine whether the cache is enabled, you only need to check the response header sent back by the server. Many browsers and tools can check this information without including Cache-Control and Expires information.

Online detection

There are also some convenient online detection services used to give suggestions on the website speed, which will detect cache settings. For example, Yahoo! The company's YSlow and Baidu webmaster tools all have corresponding functions. You can go to Baidu to check it. Currently, you do not need to log on to it.

Cache policy

Set long cache time for static resources

Some resources will not change for a long time, such as the logo image, jQuery library, and font of the website. Therefore, you can set the "never expire" cache time for them, for example, to 10 years.

Make sure the file modification takes effect

Sometimes we modify some resources, such as the jQuery version or the CSS style of the website. If these resources have been cached, you must wait until the cache expires before you obtain the new version unless you manually refresh the page. In this case, how does one force the browser to re-download? The most effective method is to include version information in the file names of such resources and modify the file names accordingly after the changes. After the browser finds that the file is changed, it cannot use the cache and will download it again.

Exercise caution when setting the expiration time for HTML documents

In most cases, requests for other images, CSS, JavaScript, and other resources come from a single HTML document. For such pages, you should set a relatively short expiration time, or simply do not set it. If such a page is cached, the file names and other information of the resources contained in the page will be cached together, making it difficult to ensure that the updates take effect immediately for users.

Do not use Query String when referencing static resources

Query String is like? Key = val string, such

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

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

Cache setting method

Apache

For Apache servers, you can use the mod_expires module to set the max-age command for the ExpiresHTTP header or Cache-ControlHTTP header. Edit the. htaccess file in the corresponding directory or directly modify the Apache configuration file (which may be httpd. conf or apache2.conf depending on the server system version.

Set file category

You can use ExpiresByType to set the expiration date for a certain Type of files based on the object's MIME Type. For example:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 2 weeks"
ExpiresByType image/x-icon "access plus 6 months"
ExpiresByType image/gif "access plus 6 months"
ExpiresByType image/png "access plus 6 months"
ExpiresByType image/jpeg "access plus 6 months"
ExpiresByType video/x-flv "access plus 6 months"
ExpiresByType application/pdf "access plus 6 months"
</IfModule>

Access plus 1 week indicates that the cache expiration is set to one week after the access time (that is, the current time. If you replace access with modification, the cache expiration time is set to one week after the file modification time. Available time units include:

Years
Months
Weeks
Days
Hours
Minutes
Seconds

It can be combined at different times, 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 file extension

If you want to specify cache rules based on the extension, you can use FilesMatch with the regular expression. For simplicity, I only specify ExpiresDefault. It takes effect only when the corresponding file does not have any other rules (including the cache rules in the upper directory.

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

Set certain files

Similarly, you can enable specific cache policies for certain files. Note that vertices (.) in the file name must be escaped.

<IfModule mod_expires.c>
<FilesMatch "^ (example \. css | example \. js) $">
ExpiresActive on
ExpiresDefault "access plus 1 week"
</FilesMatch>
</IfModule>

Set all files in a folder

A convenient way for static files is to put all the files in a directory and set all the files in the directory. However, you need to avoid other rules from overwriting ExpiresDefault.

<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 10 years"
</IfModule>

Nginx

Note: This cache is a pointer to the browser cache, not the server data cache.

Knowledge Point: location expires command

Add

Location ~ \. (Jpg | jpeg | png | gif) $ {
Expires 1d;
}

Location ~ \. Js $ {
Expires 1 h;
}

If the information flow is fast, you can also use the last_modified and etag functions without using the expires command (mainstream web servers support the two header information)

Principle:
Response: calculate the response content signature, etag, and last modification time.
Request: send etatg and If-Modified-Since header information.
After the server receives the message, it determines whether the etag is consistent and whether the last modification time is later than if-Modifiled-Since. if the server content is detected to be changed, 304 is returned, and the browser will know that the content has not changed, use cache directly.

304 has one more request than the above expires command, but has less transmission content than the 200 status.

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.