search
HomeBackend DevelopmentPHP TutorialHow to use Apache mod_expires and mod_headers to implement file caching and mod_deflate compressed output

1. Use mod_deflate module to compress output (start gzip)

Enablemod_deflate

sudo a2enmod deflate
sudo /etc/init.d/apache2 restart

Add

<IfModule mod_deflate.c>
#单独设置需要压缩的类型
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

in httpd.conf. By default, all output needs to be compressed, and only some are excluded.

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE #插入过滤器,gzip所有输出
#设置不压缩的类型
SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI .(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI .(?:pdf|doc)$ no-gzip dont-vary
</IfModule>

2. Use Apache mod_expires and mod_headers to implement file caching


Openmod_expires Use mod_expires with mod_headers

sudo a2enmod expires
sudo a2enmod headers
sudo /etc/init.d/apache2 restart

, in httpd. conf, add

<IfModule mod_expires.c>
ExpiresActive on #开启
ExpiresDefault A300 #默认
ExpiresByType text/html A300
ExpiresByType text/css A2592000 # 30天
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType application/x-javascript A2592000
</IfModule>

Using mod_headers, add

<IfModule mod_headers.c>
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
<FilesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=18000, public, must-revalidate"
</FilesMatch>
<FilesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=3600, must-revalidate"
</FilesMatch>
</IfModule>

to httpd.conf
3.Cache-Control description:


#The cache of web pages is controlled by the "Cache-control" in the HTTP message header. Commonly used Values ​​include private, no-cache, max-age, must-revalidate, etc. The default is private. Its function is divided into the following situations according to different re-browsing methods:


(1) Open a new window
The value is private, no-cache, must-revalidate, then the server will be accessed again when a new window is opened.
If a max-age value is specified, the server will not be accessed again within this value, for example:
Cache-control: max-age=5 (indicates 5 seconds after accessing this web page) Accessing again within seconds will not go to the server)
(2) Press Enter in the address bar
If the value is private or must-revalidate, the server will only be accessed the first time, and will not be accessed again.
If the value is no-cache, it will be accessed every time.
If the value is max-age, it will not be accessed again before expiration.
(3) Press the back button
If the value is private, must-revalidate, max-age, it will not be accessed again.
If the value is no-cache, it will be accessed repeatedly every time
( 4) Press the refresh button
No matter what the value is, it will be accessed repeatedly

Cache-Control (regular header, HTTP1.1)
.public: (Response header only)
Response: Inform cachers of any channel that the response can be cached unconditionally.
.private (Only For the response header)
Response: Inform the cacher (as far as I know, it refers to the user agent, the local cache of common browsers. The user also refers to the system user. But perhaps, it should not be excluded that some gateways can Identify each end user), only cache the response for a single user. And you can specify a certain field. For example, private - "username", the header content named username in the response header will not be shared and cached.
.no-cache:
Request: Inform the cacher that the original request must be forwarded exactly as it is, and inform any cachers not to directly use your cached copy to fool people. You need to go Forward my request and verify your cache (if any). Corresponding noun: end-to-end reloading.
Response: Allow cachers to cache copies. So its actual value is to always force cachers to calibrate Verify the freshness of the cache. Once freshness is confirmed, you can use the cached copy as a response. no-cache, you can also specify an included field, such as a typical application, no-cache=Set-Cookie. The result of this is to inform Cache, for the Set-Cookie field, you should not use cached content. Instead, use Xindi. Other content can be cached.
.no-store:
Request: inform, request and responses are prohibited from being cached. (Perhaps for privacy reasons)
Response: Same as above.
.max-age:
Request: Force response cacher, according to this value, Verify freshness. That is, compare it with its own Age value and the request time. If the max-age value is exceeded, server-side verification is forced to ensure that a fresh response is returned. Its function is essentially similar to traditional Expires. But the difference is that Expires is compared based on a specific date value. Once the cacher's own time is inaccurate, the result may be wrong. Max-age obviously does not have this problem. Max-age also has a higher priority than Expires.
Response: Similar to the above, except that the sender is different.
.max-stale:
Request: Meaning, I allow the cacher to send one, and it will not expire A stale cache that exceeds the specified number of seconds.
Response: Same as above.
.must-revalidate (response header only)
Response: Meaning, if the cache is past fresh period, you must re-verify instead of trying to return a cache that is not in the fresh period. The difference from no-cache is that no-cache completely ignores the concept of fresh period and always forces re-validation. In theory, must-revalidate is more Saves traffic, but compared to no-cache, it may not always be so accurate. Because even if the cacher thinks it is fresh, there is no guarantee that the server has not been updated. If the cacher is a caching proxy server, if it tries to When revalidating, if the original server cannot be connected, a stale copy in the cache is not allowed to be returned. Instead, a 504 Gateway timeout.
.proxy-revalidate(only Response header)
Response: The restriction is similar to must-revalidate. The difference is the scope of the acceptor. proxy-revalidate is to exclude the user agent's cache. That is, its rules do not apply to the user agent's local Cache.
.min-fresh(request header only)
Request: Inform the cacher that if the current time plus the value of min-fresh exceeds the expiration time of the cache, a new one will be given to me. In fact, I personally feel that its function is somewhat similar to max-age. But it is larger. The difference is semantic.
.only-if-cached: (only request header)
Request: Inform the cacher that I want the content to come from the cache, and I don’t care about being cached. Cache response, whether it is fresh.
.s-maxage(response header only)
Response: The only difference from max-age is that s-maxage only applies to shared cache . does not refer to the local cache of the user agent, such as the cache for a single user. In addition, s-maxage has a higher priority than max-age..cache-extension (cache-extension is a general name. It refers to All custom, or extended, instructions, both the client and the server can customize and extend Cache-Control related instructions.) Then, in fact, we can do this Cache-Control:max-age=300, custom-directive = xxx, public. In this way, we define an extension directive collectively called cache-extension. If the corresponding client or server does not recognize this directive, it will be ignored.
.no-transform
Request: Tell the agent not to change the media type, such as jpg, you changed it to png.
Response: Same as above.

This article explains how to use Apache mod_expires and mod_headers Implement file caching and mod_deflate compressed output. For more related content, please pay attention to the PHP Chinese website.

Related recommendations:
Introduction to HTML5 history API

About bubbling, dichotomy insertion, quick sort algorithm Introduction

#Explain the related content of PHP file download class that supports breakpoint resume transfer

The above is the detailed content of How to use Apache mod_expires and mod_headers to implement file caching and mod_deflate compressed output. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.