How to extract some value from cookie in nginx

2019-03-11 18:00发布

I am new to Nginx and hope to get some help.

I want to extract certain data (certain fields set by my PHP scripts) from browser cookie in nginx so that I can log it. If possible, I want to do this just by modifying nginx configuration.

Any pointer/help would be greatly appreciated.

标签: nginx
3条回答
祖国的老花朵
2楼-- · 2019-03-11 18:40

You can access cookie values by using the $cookie_COOKIE_NAME_GOES_HERE variable.

See Nginx Documentation

查看更多
对你真心纯属浪费
3楼-- · 2019-03-11 18:45

If anyone is using the previous answer with several different cookies in the response the correct regex is:

map $http_cookie $auth_header {
    default "";
    "~*OAuth.AccessToken=(?<token>[^;]+)" "Bearer $token";
  }

or more general usage:

map $http_cookie $auth_header {
    default "";
    "~*yourCookieName=(?<variable>[^;]+)" "the value you wanna set $variable";
  }
查看更多
唯我独甜
4楼-- · 2019-03-11 18:48

Here's an example to extract an HttpOnly cookie and pass it on to a RESTful api as an OAuth Bearer token:

http {

  map $http_cookie $auth_header {
    default "";
    "~*OAuth.AccessToken=(?<token>.+)" "Bearer $token";
  }

  server {
    listen                443 ssl;

    ssl_certificate       /etc/nginx/certs/nginx.crt;
    ssl_certificate_key   /etc/nginx/certs/nginx.key;

    proxy_set_header      Authorization $auth_header;

    location / {
      proxy_pass          https://rest-api-host.domain.com/;
    }

  }

}
查看更多
登录 后发表回答