How To Redirect Based on Cookie Value in htaccess


redirect based on cookie value in .htaccess

Sometimes, you may need to redirect website visitors to specific web pages, based on their cookie value. Let us look at how to redirect based on cookie value in .htaccess.

 

How To Redirect Based on Cookie Value in htaccess

Here are the steps to redirect based on cookie value in .htaccess. Before you proceed, please ensure that you have enabled .htaccess file on Apache web server. Here are the steps to do it:

Place your .htaccess file in the folder of your website (/var/www/html).

 

1. Open .htaccess file

Let’s say you want to redirect users from /product/web-page to /solutions/new-web-page based on cookie value id=123. So create a new blank .htaccess file at the folder where you want to setup the redirect (/var/www/html/product)


$ sudo vim /var/www/html/product/.htaccess

 

2. Redirect based on cookie value

Let’s say you want to redirect users from /product/web-page to /solutions/new-web-page based on cookie value id=1234, then add the following lines of code in your .htaccess file.


RewriteEngine on
RewriteCond %{HTTP_COOKIE} ^id=([0-9]*)$ [NC]
RewriteRule .* /product/web-page/%1 [R=301,L]
RewriteRule .* /solutions/new-web-page [R=301,L]

 

However, in the above case, please ensure that .htaccess is applicable only to the old page and not the redirected page. Otherwise it will give you an infinite loop. So place the .htaccess file in /product/

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

 

 

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!