如何仅有时在Nginx中添加标头 [英] How to add headers in nginx only sometimes
问题描述
我有一个API服务器的nginx代理. API有时会设置缓存控制标头.如果API没有设置缓存控件,我希望nginx覆盖它.
I have a nginx proxy to a API server. The API sometimes sets the cache control header. If the API hasnt set the cache control I want nginx to override it.
我该怎么做?
我想我想做这样的事情,但这没用.
I think I want to do something like this, but it doesnt work.
location /api {
if ($sent_http_cache_control !~* "max-age=90") {
add_header Cache-Control no-store;
add_header Cache-Control no-cache;
add_header Cache-Control private;
}
proxy_pass $apiPath;
}
推荐答案
在这里您不能使用if
,因为if
是重写模块的一部分,是在请求处理的早期阶段进行评估的,调用proxy_pass
并从上游服务器返回标头之前的方式.
You cannot use if
here, because if
, being a part of the rewrite module, is evaluated at a very early stage of the request processing, way before proxy_pass
is called and the header is returned from the upstream server.
解决问题的一种方法是使用map
指令.仅在使用map
定义的变量时才对其进行评估,这正是您在此处需要的.粗略地讲,这种情况下的配置如下所示:
One way to solve your problem is to use map
directive. Variables defined with map
are evaluated only when they are used, which is exactly what you need here. Sketchily, your configuration in this case would look like this:
# When the $custom_cache_control variable is being addressed
# look up the value of the Cache-Control header held in
# the $upstream_http_cache_control variable
map $upstream_http_cache_control $custom_cache_control {
# Set the $custom_cache_control variable with the original
# response header from the upstream server if it consists
# of at least one character (. is a regular expression)
"~." $upstream_http_cache_control;
# Otherwise set it with this value
default "no-store, no-cache, private";
}
server {
...
location /api {
proxy_pass $apiPath;
# Prevent sending the original response header to the client
# in order to avoid unnecessary duplication
proxy_hide_header Cache-Control;
# Evaluate and send the right header
add_header Cache-Control $custom_cache_control;
}
...
}
这篇关于如何仅有时在Nginx中添加标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!