54

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.

kee
  • 10,969
  • 24
  • 107
  • 168

3 Answers3

78

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

See Nginx Documentation

Dayo
  • 12,413
  • 5
  • 52
  • 67
  • 21
    Just to save someone's time: this method only works for cookies with alphanumeric characters and '_'. If you have a cookie called user.id or user[id] (for example) you have to use $http_cookie with the nginx map function http://nginx.org/en/docs/http/ngx_http_map_module.html#map – LuisClemente Apr 12 '16 at 13:23
  • 3
    @LuisClemente - any chance of a snip'it of how you would do this?? – Guy Jun 07 '16 at 13:53
30

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";
  }
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
andresbravog
  • 583
  • 5
  • 9
  • Brilliant thanks - One tiny optimization: you don't need the `default "";` because per docs: _When default is not specified, the default resulting value will be an empty string._ – randomsock Nov 06 '22 at 12:07
23

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/;
    }

  }

}
  • 5
    For anyone using this answer, note the `[^;]` in andresbravog's answer. That's important, because the regex in this answer will only work if the OAuth.AccessToken is the last/only cookie. – Bob Lauer Mar 28 '18 at 17:32