拒绝访问根文件夹和文件,但允许通过.htaccess子文件夹和文件

clj7thdc  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(201)

如何拒绝列出父/根文件的内容,但允许访问所有子文件夹及其文件?示例

**-Root Folder (Do not access)**
    -index.php (cannot be accessed)
    -demo.php (cannot be accessed)
    -.htaccess (for achieving this)
    **-Subfolder-1 (Grant access all files and folders)**
        -index.php
        -example.php
        -Subfolder-1 -Subfolder
    **-Subfolder-2 (Grant access all files and folders)**
        -index.php
        -example.php
        -Subfolder-2 -Subfolder
eulz3vhy

eulz3vhy1#

默认行为是允许访问,因此您可以使用mod_rewrite阻止对根目录中文件的访问。
例如:

RewriteEngine On

# Block access (403 Forbidden) to the root folder itself
RewriteRule ^$ - [F]

# 403 Forbidden for any file request in the document root
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^[^/]+\.\w{2,5}$ - [F]

上面的第二个规则只匹配对根目录中的文件(包括文件扩展名)的请求。如果此请求也Map到实际文件,则返回“403禁止”响应。如果此请求没有Map到真实的文件,则返回标准的“404未找到”响应(默认情况下)。
但是,如果您只想为所有对根目录中文件的请求发送404(或403)(看起来像什么),请使用下面的代码,删除前面的 condition

# 404 Not Found for any request that looks like a file request in the document root
# - including the root directory itself
RewriteRule ^([^/]+\.\w{2,5})?$ - [R=404]

通过将整个模式设置为可选(即,用^(.....)?$括起来),它也匹配根目录。

相关问题