apache redirect by cookie

How to Redirect in Apache based on Cookie

Apache web server allows you to redirect requests in numerous ways based on IP address, country, location, URL string and more. Sometimes you may need to redirect in Apache based on cookie value. In this article, we will look at how to check cookie value and redirect URL based on its cookie, in Apache server.

How to Redirect in Apache based on Cookie

Here are the steps to redirect in Apache based on Cookie. Please ensure that you have enabled mod_rewrite (.htaccess) before you proceed. Here are the steps to enable .htaccess in Apache.

1. Open .htaccess file

Open .htaccess file in a text editor.

$ sudo vi /var/www/html/.htaccess

2. Redirect based on Cookie

Let us say you want to redirect URLs with cookie value test other than 10 to HTTPS versions. In such cases, add the following lines to your .htaccess file.

RewriteCond %{HTTP:Cookie} (^|;\ *)test=([^;\ ]+)
RewriteCond %2 !=10
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]

Let us look at the above lines one by one. In the first line, we check HTTP Cookie header to check if it contains test cookie variable. Next, we check if its value is not 10. All matching URLs are redirected to HTTPS version of requested URLs.

If you want to check a different cookie variable, just replace test in RewriteCond above with your variable name e.g data

RewriteCond %{HTTP:Cookie} (^|;\ *)data=([^;\ ]+)

If you want to redirect these URLs to a different domain mysite.com, just update the last line.

RewriteRule ^ https://mysite.com%{REQUEST_URI} [L,R]

3. Restart Apache Server

Restart Apache server to apply changes.

$ sudo service apache2 restart

In this article, we have learnt how to redirect based on cookie value in Apache server. You can modify the RewriteCond and RewriteRule in above steps to check different cookie values and redirect them to different domains/subdomains as per your requirement.

Also read :

How to Redirect in Apache Based on Hostname
How to Block URL Pattern in Apache
How to Redirect Port 80 to 8080 in Apache
How to Parse JSON in NodeJS
How to Monitor Apache Server with mod_status

Leave a Reply

Your email address will not be published. Required fields are marked *