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.

1

3 Answers 3

78

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

See Nginx Documentation

2
  • 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 nginx.org/en/docs/http/ngx_http_map_module.html#map Apr 12, 2016 at 13:23
  • 3
    @LuisClemente - any chance of a snip'it of how you would do this??
    – Guy
    Jun 7, 2016 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";
  }
1
  • 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 6, 2022 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/;
    }

  }

}
1
  • 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, 2018 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.