Answer to the main question:
No, at least not as you imagine. The file is called .ht
access
because they are "distributed configuration files" and of course configuration && access handling must happen first - therefor you can't get "PHP session variable" because it simply comes after the processing of the .htaccess
I will show you some workarounds below, but before - you should pay attention to this:
Is this really necessary? - suggested solutions:
If you just want to redirect filepath / by logged-in user - .htaccess is NOT the way - use just bla.php
as address and then in php file do the redirect - something like this:
<?php
session_start();
header("Location: folder/".$_SESSION['foo']."/file.png");
exit();
?>
However if you can't change the source URL, you will first have to redirect bla.png
to bla.php
but I guess you know how to do that :-)
In frameworks using MPV/MVC model there are often scripts for "routing" for a reason - e.g. this one.
Optionally you could make a "php-router" from this script adding some other PHP-relying redirects while using if/elseif/else
or case
to choose what will happen - where the redirect will go.
OR
You are probably using a session anyway - so why just don't generate the url straight in PHP like:
$url = "example.com/bla.png?foo=".$_SESSION['foo'];
+ regexp in .htaccess
or even:
$url = "example.com/folder/".$_SESSION['foo']."/file.png";
Anyway I guess you are redirecting because you can't (for some reason) do that. :-)
Workarounds
If you are still persuaded that you have to do this in .htaccess file here are some workarounds
1) Use cookies
In modern days cookies are often available, so if you "trust" your client's cookies, you could make a redirect rule based on a HTTP_COOKIE
server-variable - assuming you've stored cookie called "foo
" before:
RewriteCond %{HTTP_COOKIE} ^(.*)foo=([-_a-zA-Z0-9]+)(.*)$ [NC]
RewriteRule ^bla.png$ /folder/%2/file.png [R=307,NC,L]
#possibly use 302 if you like dinosaurs
As you can see the trick is to create condition checking HTTP_COOKIE
server-variable for some condition. It basicly says:
Is there a COOKIE called "foo" which contains only "-, _, lower or upper case letters or numbers"?
If so - redirect example.com/bla.png to example.com/folder/CURRENT_FOO_VALUE/file.png
[flags]: 307 redirect (R=307), don't mind letter-case (NC), don't apply other rules (L)
Good point is that HTTP_COOKIE
server-variable is structured in this way:
name=value; name2=value2
2) NOT recommended - other workarounds:
a) read session to HTTP_SESSION
environment variable using mod_session
See the apache manual for mod_session for more info how to read session into the HTTP_SESSION
env. variable. The approach then would be the same as for the "COOKIE-workaround".
b) store needed info in a text file and read it with the RewriteMap
directive as @Chris suggested
But again you will somehow have to detect which 'foo' is it so maybe SSL_SESSION_ID
or some other $_GET/$_POST
parameters?