.htaccess重定向(如果直接访问文件夹)

问题描述:

文件夹结构:

myproject/
 documents/
   1/
    sample.pdf

我允许用户查看.pdf文件,但是当直接通过url访问时不允许查看.如果有人直接使用下面的网址访问它,它将重定向到拒绝访问页面.

I am allowing user to view the .pdf file but do not allow to view it when access directly through url. If someone access it using directly using below url, it redirects to access denied page.

http://localhost/myproject/documents/1/sample.pdf

用于实现此目的的代码是

The code used to achieve this is

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost .*$ [NC] 
RewriteRule \.(pdf)$ denied.php [L]

在进一步测试中,我发现虽然不允许直接文件访问,但是用户仍然可以了解文件上载路径并可以导航到docuemnt文件夹.

Upon further testing, I found that although direct file access is not allowed, but user can still get to know the file upload path and can navigate to docuemnt folder.

http://localhost/myproject/document/

列出所有上传的文件.

如果使用URL直接访问document文件夹或document文件夹下的子文件夹,如何限制用户.

How can I restrict user, if document folder OR sub-folders under document folder are accessed directly using URL.

无论当前如何访问文件夹,都会显示该文件夹内的文件.

The files inside the folder will be shown regardless of folder access as its happening now.

您可以在RewriteEngine行下方插入 ,以拒绝直接输入/document URL:

You can insert just below RewriteEngine line to deny direct entry to /document URL:

RewriteCond %{THE_REQUEST} /document [NC]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . - [F]