I'm working on a solution to a problem where users could potentially access images (in this case PDF files) stored in a folder off the server root. Normally, my application validates users through PHP scripts and sessions. What isn't happening right now is preventing non-logged in users from potentially accessing the PDFs.

The solution I'm looking for would (I think) need to be tied in with Apache. I saw an interesting solution using RewriteMap & RewriteRule, however the example involved putting this in an .htaccess file in the PDF directory. Can't do that with Apache (error: RewriteMap not allowed here). I believe the rewrite directives need to go in my httpd.conf, which I have access to.

So the example I found (that resulted in 'rewritemap not allowed here') is here:

RewriteEngine On
RewriteMap auth prg:auth.php
RewriteRule (.*) ${auth:$1}

auth.php just checks PHP session and redirects to a login script if needed.

I'm reading that I have to place this in my httpd.conf. How would I specify that the RewriteMap should only occur on a specific directory (including subdirectories)?


I would probably handle it using RewriteRule instead of RewriteMap. Create a mod_rewrite rule that redirects pdf requests to a php file

RewriteEngine on
RewriteRule ^(.*\.pdf)$ /path/to/auth.php?i=$1

You can then have the auth.php authenticate the session and spit out the actual contents of the PDF file. I did the same using a RewriteRule and jpg files.

RewriteRule ^([^thumb].*\.[jJ].*)$ /auth.php.php?i=$1

I then uses auth.php to modify the image based on session and other factors and then spit it back out to the client. Eg:

$last_modified = gmdate('D, d M Y H:i:s T', filemtime ($image));
header("Last-Modified: $last_modified");
header("Content-Type: image/jpeg");

You can also do some cool things like adding a unique watermark and any other processing you'd like on the image and I suspect with the write functions, on a PDF file.

  • This is definitely the more flexible way of achieving what you want. – Ladadadada Mar 29 '12 at 20:42

You can wrap those directives in either a <Location /directory> block (if you want to match a URI) or a <Directory /var/www/html/directory> block (if you want to match a filesystem path).

Or you can just change the pattern part of the RewriteRule to only match the URI path you want:

RewriteRule (^/directory.*) ${auth:$1}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.