Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx, how to add header if it is not set

I want to add a header (Cache-control) in nginx only if it is not set.

I need to increase cache time in some case via the header in nginx.

like image 526
Dimmduh Avatar asked Nov 27 '12 11:11

Dimmduh


People also ask

How do I enable headers in nginx?

To enable the X-Frame-Options header in Nginx, add the following line in your Nginx web server default configuration file /etc/nginx/sites-enabled/example. conf: add_header X-Frame-Options "SAMEORIGIN"; Next, restart the Nginx service to apply the changes.

Does nginx pass headers?

By default, nginx does not pass the header fields “Date”, “Server”, “X-Pad”, and “X-Accel-...” from the response of a proxied server to a client.

What is a header in nginx?

The HTTP headers in NGINX are split in two parts: the input request headers (headers_in structure) and the output request headers (headers_out structure). There is no such an entity as a response, all the data is stored in the same single request structure.


1 Answers

You can use map to populate a variable $cachecontrol. If $http_cache_control (the header from the client) is empty, set a custom value. Otherwise (default) reuse the value from the client.

map $http_cache_control $cachecontrol {
    default   $http_cache_control;
    ""        "public, max-age=31536000";
}

Afterwards you can use that variable to send the upstream header.

proxy_set_header X-Request-ID $cachecontrol;

For the follow-up question from jmcollin92, I wrote the following in SO Documentation, now transcribed here.

X-Request-ID

nginx

Reverse proxies can detect if a client provides a X-Request-ID header, and pass it on to the backend server. If no such header is provided, it can provide a random value.

map $http_x_request_id $reqid {                                                 
    default   $http_x_request_id;                                               
    ""        $request_id;                                                      
}

The code above stores the Request ID in the variable $reqid from where it can be subsequently used in logs.

log_format trace '$remote_addr - $remote_user [$time_local] "$request" '        
                 '$status $body_bytes_sent "$http_referer" "$http_user_agent" ' 
                 '"$http_x_forwarded_for" $reqid';                              

It should also be passed on to the backend services

location @proxy_to_app {
    proxy_set_header X-Request-ID $reqid;
    proxy_pass   http://backend;
    access_log /var/log/nginx/access_trace.log trace;
}
like image 51
Stefan Kögl Avatar answered Sep 28 '22 08:09

Stefan Kögl