How to rewrite a directory to a cookie value in .htaccess?

Viewed 38
$val = substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz0123456789", 12)), 0, 12);
setcookie('sub' , $val , time() + (86400) , '/');

example.com/folder/file.php should be rewritten to the value of $_COOKIE['sub'] e.g. example.com/6df1fcb7aba6/file.php
How can I do that?

I tried this:

RewriteCond %{HTTP_COOKIE} !^.*sub.*$ [NC]
RewriteRule %{HTTP_COOKIE} !^.*sub.*$/(.*) folder/$1

, but doesn't work

1 Answers

You can do something like the following in the root .htaccess file using mod_rewrite:

RewriteEngine On

RewriteCond %{HTTP_COOKIE} (?:^|;|\s)sub=([a-z0-9]{12})(?:$|;)
RewriteRule ^folder/(file\.php)$ %1/$1 [L]

The above states:

  1. Given a request for /folder/file.php
  2. And the cookie sub exists with a 12 char alphanumeric (lowercase) value.
  3. Rewrite the request to /<sub-cookie-value>/file.php

The %1 backreference contains the value of the sub cookie, providing it meets the criteria of being a 12 char alphanumeric (lowercase) value.

The $1 backreference simply contains file.php as captured from the RewriteRule pattern.

RewriteCond %{HTTP_COOKIE} !^.*sub.*$ [NC]
RewriteRule %{HTTP_COOKIE} !^.*sub.*$/(.*) folder/$1

The RewriteRule pattern (first argument) is a regex that matches against the requested URL-path, so %{HTTP_COOKIE} (seen as a literal string) will never match, so the rule does nothing. However, the syntax of the 3rd argument (flags) is entirely invalid so is likely to result in a 500 Internal Server Error ("bad flags delimiter").

The RewriteCond directive is checking that the string sub does not occur anywhere in the Cookie HTTP request header, which is not what you want to do. You need to check that sub is present and extract the value.

Related