How to Redirect Based on Cookie Value in NGINX


redirect based on cookie value nginx

Sometimes, you may need to redirect website visitors to specific pages based on cookie value. Let us take a look at how to redirect based on cookie value in NGINX.

 

How to Redirect Based on Cookie Value in NGINX

Here are the steps to redirect based on cookie value in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. You will typically find it at /etc/nginx/nginx.conf


$ sudo vim /etc/nginx/nginx.conf

 

2. Add redirect based on cookie value

Let’s say you have a cookie “name=value” that you want to check on your home page and redirect users to /news if it is present, then add the following code to your nginx.conf file. We use the server variable $cookie_name to check the cookie and redirect users using the return directive.


server {
 listen 80;
 server_name your_domain.com;

 location ~* ^/$ {
  if ($cookie_name = "value") {
   return 301 http://example.com/news/;
  }
 }
}

 

3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!