簡體   English   中英

使用 .htaccess 限制對目錄的直接訪問

[英]Limit direct access to directory using .htaccess

我有以下文件夾結構,其中運行着 web 應用程序:

/root/public/index.php

我在/root中有一個.htaccess將所有請求重定向到/root/public但我也可以通過在我的請求中添加/public目錄來訪問我的內容,例如目前我可以做的

  • www.example.com/public/index.php
  • www.example.com/index.php

兩者都導致相同的資源,但我只希望人們通過訪問資源來訪問資源,如果他們嘗試直接訪問/public目錄,則返回錯誤

www.example.com/index.php

我當前的.htaccesss看起來像這樣:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^(.*)$ public/ [L]
</IfModule>

我在這里缺少什么來阻止通過 URL 訪問我的/public文件夾?

我已嘗試應用 WordPress 使用的一些重寫規則,但按照此處的指南,這對我的用例不起作用: https://wordpress.org/documentation/article.htaccess/

你可以這樣做:

RewriteEngine On

# Block direct requests to the "/public" subdirectory
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^public/ - [F]

# Rewrite all requests to "/public/index.php"
RewriteRule ^ public/index.php [END]

(不需要<IfModule>包裝器,應該將其刪除。)

針對REDIRECT_STATUS環境變量的檢查可確保僅檢查直接請求(來自用戶),而不檢查由稍后重寫的重寫請求。

請注意,我更改了您現有的規則以將請求直接重寫為/public/index.php因為這似乎是意圖。 (而不是依賴DirectoryIndex 。)

雖然,我想知道您如何管理您的 static 資產(如果有)?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM