Reputation: 53
I need to protect all pdf files on server through a password. Typical path to a pdf is /images/a/a2/some.pdf
My rewriting code in httpd.conf is :
RewriteEngine On
Options FollowSymLinks
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^images/([^/]*)/([^/]*)/([^/]*)^.pdf$ /download.php?file=$3& [L]
RewriteRule images/a/a2/VB-VB-41-445%29_Small.pdf$ /download.php?file=ok [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ /index.php/$1 [L,QSA]
The 5th line is added to check whether there is some problem in regular expression.
Unfortunately, the redirect doesn't work. If pdf exists it starts to load immediately. But if path doesn't exist, it works! I need the opposite result. What is wrong with code or maybe there are some config settings with mod_rewrite?
P.S. I noticed one clue to a possible answer: if i replace "images" with "asdf" in rewrite rule and try non-existing path, it redirects to download.php. But if i try non-existing path with "images", it returns 404 error. Asdf doesn't exist on the server, but images - is a true folder.
RewriteRule /images/asd.pdf /download.php?file=ok [L,QSA] - doesn't work, folder exists, file asd.pdf doesn't exist
RewriteRule /asdf/asd.pdf /download.php?file=ok [L,QSA] - works, redirects correctly to download.pdf, path doesn't exists (neither folder nor file)
RewriteRule images/a/a2/VB.pdf$ /download.php?file=ok [L] - doesn't work, redirect doesn't happen, instead an existing pdf file starts to download.
P.P.S. After some time I found that inside /images/ folder there is .htaccess file with this text:
# Protect against bug 28235
<IfModule rewrite_module>
RewriteEngine On
RewriteCond %{QUERY_STRING} \.[^\\/:*?\x22<>|%]+(#|\?|$) [nocase]
RewriteRule . - [forbidden]
</IfModule>
<IfModule expires_module>
ExpiresActive On
ExpiresDefault "access plus 1 month"
</IfModule>
Probably, it is the cause of rewriting issue.
P.P.P.S.
The problem has been solved with writing the rewrite rule in a file .htaccess inside folder /images/:
# Protect against bug 28235
<IfModule rewrite_module>
RewriteEngine On
RewriteCond %{QUERY_STRING} \.[^\\/:*?\x22<>|%]+(#|\?|$) [nocase]
RewriteRule . - [forbidden]
RewriteRule ^[^\/]+/[^\/]+/(.*)\.pdf$ ../download.php?file=$1& [L]
</IfModule>
<IfModule expires_module>
ExpiresActive On
ExpiresDefault "access plus 1 month"
</IfModule>
Upvotes: 0
Views: 1232
Reputation: 56
The PDF starts to download if exists in path because of RewriteCond %{REQUEST_FILENAME} -f directive. This tells apache that the file exists and to not proceed with the following rules. If you remove this line, the mod_rewrite will always follow rules no matter if file exists or not.
Upvotes: 1