Nginx仅在匹配的位置不包含查询字符串时如何应用proxy_ignore_headers Set-cookie?

时间:2019-04-24 20:35:30

标签: nginx nginx-location nginx-config

我需要当相同位置(根,主页-/)的请求URI不包含任何(或特定的)查询字符串时,才开始缓存并防止在用户浏览器中设置cookie,这与代理服务器正在发送的事实相反标头“ set-cookies”,请参见我为此目的尝试使用的代码:

nginx.conf (其中nGinx是前端缓存代理,而Apache是​​后端Web服务器):

location = / { 
        proxy_pass  https://115.xx.xx.xx:8443;   
        proxy_cache             my_cache;
        proxy_cache_valid       10m;


            # only if there is no query strings in request (URI without any variables, 
            # for example, exact is: https://mydomain.xyz/ ), only then ignore 
            # Set-Cookies header what means in result cache page and prevent to 
            # client's browser set cookie what webpage sent = apply following 
            # proxy_ignore_headers and proxy_hide_header commands:

                if ($args ~ "^$") { 
                    ## if req URI is https://mydomain.xyz/ , then:

                       proxy_ignore_headers    Set-Cookie;
                       proxy_hide_header       Set-Cookie;
                }



            # but when the same URI (location) contains query string (for example: 
            # https://mydomain.xyz/?rand=4564894653465), then let cache 
            # automatically disabled (as default, when nGinx see that the webpages 
            # sent header "Set-Cookie", then does not cache answer page) and allow 
            # set this cookie in user's browser (as webpage requested it):

                if ($args ~ "^rand=[:digit:]+") {  
                    ## if req URI is https://mydomain.xyz/?rand=45648 , then:

                       proxy_pass_header   Set-Cookie;
                }

}

但不幸的是,如果条件 {{} (位于位置{  })是不可能的/允许的,并且我收到错误消息:

/etc/nginx/nginx.conf:145

中的此处不允许使用

proxy_ignore_headers ”指令

所以这行不通...

我花了很多时间在Internet上找到解决方案,但从未找到目的相似的线程。

如果知道任何解决方案如何解决我的示例,请提供帮助,在此先感谢!问候

1 个答案:

答案 0 :(得分:0)

您可以使用您的if语句跳转到另一个location块。选择一个不存在的URI(例如:/bogus)并将其用作internal位置块,以不带任何参数地处理请求。

例如:

proxy_cache             my_cache;
proxy_cache_valid       10m;

location = / { 
    proxy_pass  https://115.xx.xx.xx:8443;   
    if ($args = "") {
        rewrite ^ /bogus last;
    }

    ...
}
location = /bogus {
    internal;
    proxy_pass  https://115.xx.xx.xx:8443;   
    proxy_ignore_headers    Set-Cookie;
    proxy_hide_header       Set-Cookie;
}

有关详细信息,请参见this document