Categories
Apache mod-rewrite and htaccess related Articles

How to set cookies for a specific http_host with htaccess?

4.7
(6)

Last Updated on November 11, 2021 by Amit

This article explains how to set an http cookie for a specific http_host header with htaccess file using mod_rewrite.
With mod_rewrite we can set cookies using [CO] flag.

CO is used to set cookies in htaccess when a specific RewriteRule or the rule containing “CO” flag matches.

In this article , I will show you how we can set cookies when a specific http host (domain) is requested.

Set cookie for specific host header

The solution being provided here is useful if you have multiple domains pointing to the same document root and you want to set cookies for a specific one.

Consider the following example :
This sets a cookie with the following name and value :

cookie name : mydomain
Value : example.com .
The cookie is set only if the rule matches. The rule matches if the condition is met. Here we are using the %{HTTP_HOST} condition to check the current domain name.

RewriteEngine On
#if the host = example.com
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
#run the rule and set cookies
RewriteRule .* - [CO=mydomain:example.com,L]

The rule above sets the cookie named mydomain and value example.com . You can access the cookie in your PHP script or use a rule in htaccess to check the cookie value. The rule above is not generic ,if you don’t want to set the cookie value manually , you can use the following rule instead as it sets the value of cookie automatically from the host condition

RewriteEngine On
#if the host = example.com
RewriteCond %{HTTP_HOST} ^(example.com)$ [NC]
#run the rule and set cookies
RewriteRule .* - [CO=mydomain:%1,L]

The rule examples above set the cookie successfully but there is still one important thing missing in the both examples. We forgot to set the cookie expire time or how long the cookie will survive. We need to add the validity argument to our code . The default cookie expire time is 0 which means the cookie will expire as soon as the browser window is closed.

You can set cookies expire time in minutes starting from 1. To set the cookie validity upto 1 hour we can use 60 as the validity argument.

RewriteRule .* - [CO=mydomain:%1,60,L]

Related article : How to set cookies with mod_rewrite .

How useful was this post?

Click on a star to rate it!

Average rating 4.7 / 5. Vote count: 6

No votes so far! Be the first to rate this post.

By Amit

I am a freelance web developer/designer , blogger and StackOverflow contributer from India.

Leave a Reply

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

*

code