Mo Alsaedi
Mo Alsaedi

Reputation: 709

in .htaccess, how to detect a part of a cookie name with Regex?

I'm setting up a .htaccess file to prevent access to anything within a folder unless a certain cookie is set. The issue is that the cookie name can vary as a certain ID number is attached to the end of it, and I have no control over that.

The cookie I have setup can be (frm_form30, frm_form31, etc.).

Here's the .htaccess code I have so far:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} !^.*\bfrm_form(?:\d*\.)?\d+*.*$ [NC]
RewriteRule .* / [NC,L]

I'm using this:

\bfrm_form(?:\d*\.)?\d+

as the regex that will detect any cookie starting with frm_form and ending with a two digit number. Can anyone point me in the right direction or tell me if I'm doing something completely wrong?

The code works if I use the full cookie name (ex. frm_form30), so the rest of the file --I think-- is alright.

Your help is greatly appreciated!

Upvotes: 0

Views: 199

Answers (2)

Lorenz Meyer
Lorenz Meyer

Reputation: 19895

To detect a two digit number just use \bfrm_form\d\d or \bfrm_form\d{2}.

Your regex matches any number, with decimal part or not.

Simplify your expression and send A Forbidden header instead of redirecting :

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} !\bfrm_form\d\d\b [NC]
RewriteRule .* [F]

Upvotes: 1

Mo Alsaedi
Mo Alsaedi

Reputation: 709

Here's how I solved this:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} !^.*frm_form+(?:\d*\.)?\d+.*$ [NC]
RewriteRule .* http://domain.com [NC,L]

Let me know if you think there is a better way. Thanks!

Upvotes: 0

Related Questions