Friday 27 December 2019

NGINX: expires: Set Expires and Cache-Control headers


Using ‘expires’ directive, you can set Expires and Cache-Control headers.

Syntax:  expires [modified] time;
expires  epoch | max | off;
Default: expires off;
Context: http, server, location, if in location

Example
expires    24h;
expires    modified +24h;
expires    @24h;
expires    0;
expires    -1;
expires    epoch;
expires    $expires;

Example in location context
location = /about{
  add_header url "/about";
  add_header version "1.23.4";

  expires 5m;
           
  return 200 "Hello Welcome to NGINX";
}

nginx.conf
events {
}

http {
    include mime.types;

    # Buffer size for POST submissions
    client_body_buffer_size 10K;
    client_max_body_size 4m;

    # Buffer size for Headers
    client_header_buffer_size 1k;

    client_body_timeout 60s;

    client_header_timeout 60s;

    keepalive_timeout 75s;

    send_timeout 60s;

    server {
        listen 9090;

        server_name localhost;

        location = /about{
            add_header url "/about";
            add_header version "1.23.4";
           
            expires 2m;
 
            return 200 "Hello Welcome to NGINX";
        }

        location = /not_found{
            return 404 "File can't be found";
        }
    }
}


Validate and reload the configuration
$sudo nginx -t
nginx: the configuration file /usr/local/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /usr/local/etc/nginx/nginx.conf test is successful
$
$sudo nginx -s reload


When I hit the url ‘localhost:9090/about’, I can see Expires and Cache-Control response headers.
$CURL -I localhost:9090/about
HTTP/1.1 200 OK
Server: nginx/1.17.3
Date: Wed, 16 Oct 2019 15:03:04 GMT
Content-Type: text/plain
Content-Length: 22
Connection: keep-alive
Expires: Wed, 16 Oct 2019 15:05:04 GMT
Cache-Control: max-age=120
url: /about
version: 1.23.4


Previous                                                    Next                                                    Home

No comments:

Post a Comment