Search code examples
phpapache.htaccessmod-rewriteurl-rewriting

.htaccess, use mod_rewrite to rewrite to a file OUTSIDE the web root


Here is a representation of my directory structure:

/var/www
  /html/site
    .htaccess
  /secret
    file.php

I'd like to use the .htaccess file to rewrite url requests made to http://example.com/files/1234 to the code file.php sitting outside of the webroot. This is for security reasons, the other developers I'm working with are insistent that this code sit outside of web accessible directories. So far, my .htaccess file looks like this:

RewriteEngine On
RewriteRule ^files/(.*)$ ../../secret/file.php?file_name=$1 [NC,L]

But I'm getting a 400 Bad Request when I try to do this. Is it even possible?


Solution

  • Short answer: no. The webserver can't directly access files outside of the document root. If you think about it, there would be quite a security problem if it could. What you can do is rewrite to a file within the document root that includes or reads from the file that is located outside of the root. (Moved from comments...)