can you set up cookies in nginx?

Posted November 1, 2016 74.4k views

i am working on AWS Elastic Beanstalk Instance, which runs Java application served through Nginx ( no load balancer in front, just a standalone instance )
I need to set cookie to catch client ip and client hostname. Is this possible to do it in nginx or should this be done in my Java code?

Below if my nginx configuration file:

location / {
http_version 1.1;

proxysetheader Connection $connectionupgrade;
setheader Upgrade $httpupgrade;
proxysetheader Host $host;
proxysetheader X-Real-IP $remoteaddr;
setheader X-Forwarded-For $proxyaddxforwarded_for;

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer

You can try playing around with nginxs add_header Set-Cookie.

IP address of client should be in $remote_addr and host in $Host.

You can try adding following in location block:

add_header Set-Cookie cip=$remote_addr;
add_header Set-Cookie chost=$Host;

For more control you can try

add_header Set-Cookie "cip=$remote_addr;;Path=/;Max-Age=100000";

I didn’t tried it myself, I’m not sure is it correct, but test. I will try it myself but I’m out of my test server and can’t verify now. :)