Nginx, how to add header if it is not set

2020-03-12 05:32发布

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.

1条回答
Melony?
2楼-- · 2020-03-12 05:59

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;
}
查看更多
登录 后发表回答