apache check if cookie is et

How to Check if Cookie is Set in Apache Server

Sometimes you may need to check if a cookie is set in user request and take actions accordingly. For example, you may want to redirect users to specific page, if a cookie is set. In this article, we will look at how to check if cookie is set in Apache server.


How to Check if Cookie is Set in Apache Server

Here are the steps to check if cookie is set in Apache server. Before proceeding, please ensure that you have enabled mod_rewrite (.htaccess) in your Apache server. Here are the steps to enable .htaccess in Apache.

Let us say you want to redirect users to a specific page if cookie is set in their requests.


1. Open .htaccess file

Open .htaccess file in a text editor.

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


2. Check if Cookie is Set

Typically, websites & applications provide customizations based on user locations stored in cookies. Let us say you want to check if a cookie named location is set. If it is set, then we want to redirect all URL’s beginning with /profile to /personalized_profile. In this case, add the following lines to .htaccess. Replace location with your cookie name.

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/profile/?$
RewriteCond %{HTTP_COOKIE} location=([^;]+)
RewriteRule .* http://example.com/personalized_profile/%1 [R=302,L]

Let us look at the above code. The first line enables mod_rewrite. Next line checks for requested URL to see if it begins with /profile. The third line checks if location cookie is set. Last line redirects all matching URLs to /personalized_profile.

You can change the domain example.com and URLs as per your requirements. This is just a basic configuration to help you examine requested URL for cookie value and redirect users if it is set.


3. Restart Apache

Restart Apache server to apply changes.

$ sudo service apache2 restart

In this article, we have learnt how to test if cookie is set in Apache server. You can customize the above .htaccess configuration block as per your requirements.

Also read :

How to Redirect in Apache based on Cookie
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 Monitor Apache Performance using mod_status