How to Cache-Control in Nginx
To Cache-Control in Nginx
Caching is important protocol as per as HTTP and browsing . The basic principle of content caching is to offload repetitive work from the upstream servers. There are specific directives for caching mechanisms and these directives needs to be followed by caching servers either be it in browser or a dedicated cache server.
- The cache policies are specified by the browsers and dedicated cache servers.
- The cache mechanism works with the help of cache-control header.
To Cache
First, open your configuration file by making use of the following command.
[root@linuxhelp ~]# cd /etc/nginx/conf.d/
[root@linuxhelp conf.d]# vim vir.conf
Add the following configuration in the file.
server { server_name www.linuxhelp1.com location / { root /usr/share/nginx/html index index.html index.htm } location ~.(jpg) { root /usr/share/nginx/html } }
Save and exit the configuration file once it is completed.
Now, you need to check for the syntax.
[root@linuxhelp conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
You should now restart your nginx service as follows.
[root@linuxhelp conf.d]# systemctl restart nginx
And then, you need to execute curl command. You will notice that there is no information related to Cache-control in the output.
[root@linuxhelp conf.d]# curl -I http://www.linuxhelp1.com/index1.jpg
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Mon, 05 Feb 2018 12:29:17 GMT
Content-Type: image/jpeg
Content-Length: 12871
Last-Modified: Mon, 05 Feb 2018 11:59:55 GMT
Connection: keep-alive
ETag: " 5a78473b-3247"
Accept-Ranges: bytes
So, you need to open your configuration file again.
[root@linuxhelp conf.d]# vim vir.conf
Now add expire header 48h which by default adds cache-control header also for that add the following.
server { server_name www.linuxhelp1.com location / { root /usr/share/nginx/html index index.html index.htm } location ~.(jpg) { root /usr/share/nginx/html expires 48h } }
Save and exit the configuration file
Once again restart your nginx service.
[root@linuxhelp conf.d]# systemctl restart nginx
And execute the curl command to check for Cache-Control.
[root@linuxhelp conf.d]# curl -I http://www.linuxhelp1.com/index1.jpg
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Mon, 05 Feb 2018 12:31:19 GMT
Content-Type: image/jpeg
Content-Length: 12871
Last-Modified: Mon, 05 Feb 2018 11:59:55 GMT
Connection: keep-alive
ETag: " 5a78473b-3247"
Expires: Wed, 07 Feb 2018 12:31:19 GMT
Cache-Control: max-age=172800
Accept-Ranges: bytes
You will now note that the Cache-Control is visible.
"https://www.nginx.com/blog/nginx-caching-guide/".
# nginx -t