Serve Static Assets With An Efficient Cache Policy

What is a cache policy and how to set the right HTTP cache policy to serve your static files.

Last Updated : March 12, 2019


What it means?

When a browser requests a file, the server providing the file can tell the browser how long it should cache the file. If the user re-requests the file (by revisiting your site) in this duration, the browser can use the local copy instead of re-downloading it. In this way, HTTP caching helps load your pages faster for returning users.

Static assets refers to JS, CSS and image files. Since these files are not expected to change very frequently, HTTP caching should be setup for these. Since these are served by web servers (Apache, Nginx, etc) - the web server needs to be configured for this to work.

A server tells the browser about caching a file through a cache-control header. It looks like this:

Cache-Control: public, max-age=31536000

Here, the max-age is the time in seconds, for which the browser can use the local copy of the file instead of re-downloading it.

Setup Cache Policy For Nginx

If your website is served via Nginx web server, you can update it's configuration to enable adequate caching policy:

sudo vi /etc/nginx/nginx.conf

Here, you can add the cache control policy specific settings within the server block:

server {
	..
	location ~* \.(ico|css|js|gif|jpeg|jpg|png|woff|ttf|otf|svg|woff2|eot)$ {
		expires 365d;
		add_header Cache-Control "public, max-age=31536000";
	}
}

Restart Nginx to ensure the new configuration is in action:

sudo systemctl restart nginx

Setup Cache Policy For Apache

If you use Apache2 Web Server to serve your website, you will have to update the .htaccess file within the website's root folder or the configuration file containing the addequate <VirtualHost> entry for your website:

<VirtualHost *:80>
        DocumentRoot (Your root folder here)
        ServerName (ServerName Details Here)
        ..
		<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|svg)$">
			Header set Cache-Control "max-age=31536000, public"
		</FilesMatch>
		..
</VirtualHost>

Restart your Apache web server for the new configuration to take effect:

sudo service apache2 restart

Why Cache Policy for Static Assets should not be set via PHP?

Your static assets (JS, CSS, Image files) are typically served via your web server (Apache, Nginx) and thus, cache policy for static files should not be set via PHP. However, you can definitely set HTTP headers (including cache policy headers) via PHP for specific PHP pages. However, PHP pages resources of your site are not static assets and their cache policy should be different from the one stated on this web page.

Verify Cache Policy in Action

To verify that your web server is returning the response with right cache control headers, you can use the curl command with -I flag (to view only HTTP response headers):

curl -I <YourStaticFileURLHere>

You should look for the 'Cache-Control' in the HTTP response header. If it is as below, your configuration is working as expected:

HTTP/1.1 200 OK
..
Cache-Control: max-age=31536000, public
..

HTTP Caching Gotchas

If you change the content of your static (CSS, JS, Image, etc) files due to any reason and if a returning user visits your site, the browser may show him (stale) cached file contents. To avoid this scenario, you should change the name of your static file everytime it's content changes. You can achieve this by adequate versioning or by appending last modified timestamp to the file name or through other similar mechanisms. Failure to do so may lead to broken / erronous website experiences.



Punit Sethi

About the Author

Punit Sethi has been working with large e-Commerce & B2C websites on improving their site speed, scalability and frontend architecture. He tweets on these topics here.

Also Read

Use Brotli Compression

Last Updated : April 16, 2019

Reliably serve brotli compressed files with gzip fallback while ensuring no compression overhead when serving brotli files.




哆哆女性网烧烤店起名蔬果公司起名字狼刃好听的宾馆起名超级转换秀许氏起名字公关公司起名大全起名诗词 男孩小名起名结果查询花甲开五金店起什么名字好?装饰公司起什么名字合适西甲联赛多少轮七星室内滑雪场电信怎么查话费新闻排行榜天之云地之雾商标名牌起名字牛宝起名杀神永生超人:钢铁之躯网站取名起名大全大全格式工厂绿色版楚河汉街的遗迹在哪个省顾问公司起什么名字好覃起名字塞尔达传说缩小帽男孩起名叫天什么好听亚洲男篮锦标赛以亦字起名淀粉肠小王子日销售额涨超10倍罗斯否认插足凯特王妃婚姻不负春光新的一天从800个哈欠开始有个姐真把千机伞做出来了国产伟哥去年销售近13亿充个话费竟沦为间接洗钱工具重庆警方辟谣“男子杀人焚尸”男子给前妻转账 现任妻子起诉要回春分繁花正当时呼北高速交通事故已致14人死亡杨洋拄拐现身医院月嫂回应掌掴婴儿是在赶虫子男孩疑遭霸凌 家长讨说法被踢出群因自嘲式简历走红的教授更新简介网友建议重庆地铁不准乘客携带菜筐清明节放假3天调休1天郑州一火锅店爆改成麻辣烫店19岁小伙救下5人后溺亡 多方发声两大学生合买彩票中奖一人不认账张家界的山上“长”满了韩国人?单亲妈妈陷入热恋 14岁儿子报警#春分立蛋大挑战#青海通报栏杆断裂小学生跌落住进ICU代拍被何赛飞拿着魔杖追着打315晚会后胖东来又人满为患了当地回应沈阳致3死车祸车主疑毒驾武汉大学樱花即将进入盛花期张立群任西安交通大学校长为江西彩礼“减负”的“试婚人”网友洛杉矶偶遇贾玲倪萍分享减重40斤方法男孩8年未见母亲被告知被遗忘小米汽车超级工厂正式揭幕周杰伦一审败诉网易特朗普谈“凯特王妃P图照”考生莫言也上北大硕士复试名单了妈妈回应孩子在校撞护栏坠楼恒大被罚41.75亿到底怎么缴男子持台球杆殴打2名女店员被抓校方回应护栏损坏小学生课间坠楼外国人感慨凌晨的中国很安全火箭最近9战8胜1负王树国3次鞠躬告别西交大师生房客欠租失踪 房东直发愁萧美琴窜访捷克 外交部回应山西省委原副书记商黎光被逮捕阿根廷将发行1万与2万面值的纸币英国王室又一合照被质疑P图男子被猫抓伤后确诊“猫抓病”

哆哆女性网 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化