Generally, it's not a good idea to serve protected files from within the document root. Specially, when users need to login to see/access them. When you delegate the serving to the webserver, you loose the ability to programmatically check if the user is logged in, since there's no way for the Apache web server to know if a user is authenticated within your PHP application. Once a user knows about the file URL, she can access the file without being logged in to the system.
There's a workaround which I'll get you through. But I strongly suggest you to place the files outside of your webroot and develop a script to deliver them when accessed. This way you can check for an authenticated and authorized session when serving the file.
However, if you insist to go this way, there's a workaround. Let's lay out a sample directory structure:
/path/to/web/document/root
├── manual
│ └── .htaccess
│ └── file1.pdf # protected
│ └── file2.pdf # protected
│ └── file3.epub # protected
├── documentation.php
├── listing.php # protected
└── .htaccess
You want the files in the manual/
directory to be protected and only access when users are logged-in. So, you put the directives below in your manual/.htaccess
file:
RewriteEngine on
RewriteRule ^ /documentation.php [R]
# Your own rewrite rule has a syntax error and
# causes a 500 internal error
This will redirect all requests to the documentation.php
file in the parent directory. Drop the R
flag if you don't need an external redirect.
As you said, now the problem is that any request to the files inside manual/
is getting redirected to the documentation file.
The workaround is to check the HTTP_REFERER
header and make sure that the request is coming from the listing.php
file.
RewriteEngine on
# Feel free to change example.com with your own domain
RewriteCond %{HTTP_REFERER} !^http://www.example.com/listing.php$
RewriteRule ^ /documentation.php [R]
This way any direct request to manual/file2.pdf
will result in a redirection to documentation.php
, but if a user clicks on a link in listing.php
she can access the file without any problem.
If you need to make the referer condition more generic, see this article:
Referrer Checking with .htaccess
Be warned that a user can easily spoof the HTTP_REFERER
header and thus access the files without the need to be logged-in. The only real bullet-proof way to implement this is what I said at the beginning of this post.
You might also want to protect the manual/
directory using basic http auth. But this way, users need to enter another username/password combination to access that folder.