Setting cookie with initial referer value

Dear mailing list

I am in the process of migrating our sites away from Apache onto
nginx. I only need one final thing before I can move to nginx:

On our apache servers we set an cookie (named ref) with the initial
page referer that a user accessed our site with. This is done under
Apache like this:

Referer tracking

SetEnvIf Cookie “.ref=.” referer_cookie_exists
SetEnvIf Referer “(.*)” stripped_referer=$1
Header add Set-Cookie “ref=%{stripped_referer}e; path=/; HttpOnly”

First we check to see if the cookie already exists - if the cookis
doesn’t exist then it is set with the value of the referer that the
user accessed the site with. We do this so we can track where people
visit us from.

I have looked at a similar solution for nginx but have not been able
to come up with one. Anyone got an idea on how to solve this problem?

Kind regards,