2012-07-30 136 views
78

我有以下.htaccess文件:如何拒絕訪問文件在.htaccess

RewriteEngine On 
RewriteBase/

# Protect the htaccess file 
<Files .htaccess> 
Order Allow,Deny 
Deny from all 
</Files> 

# Protect log.txt 
<Files ./inscription/log.txt> 
Order Allow,Deny 
Deny from all 
</Files> 

# Disable directory browsing 
Options All -Indexes 

我試圖禁止遊客進入下列文件:

domain.com/inscription/log.txt 

但我以上不起作用:我仍然可以從瀏覽器遠程訪問文件。

回答

137

在htaccess文件中,<Files>指令的範圍僅適用於該目錄(爲了避免在子目錄的htaccess中的規則/指令從父級應用取代應用時出現混淆,我想這應該避免混淆。

所以,你可以有:

<Files "log.txt"> 
Order Allow,Deny 
Deny from all 
</Files> 

在htaccess文件在你的inscription目錄。或者你可以使用mod_rewrite來排序的處理這兩種情況下拒絕訪問htaccess文件以及log.txt的:

RewriteRule /?\.htaccess$ - [F,L] 

RewriteRule ^/?inscription/log\.txt$ - [F,L] 
+0

如果您使用的是IIS,在web.config文件中做到這一點,而不是。 – 2014-11-03 16:33:09

+0

使用重寫規則會拒絕我自己的代碼訪問* .txt的內容。你如何解決這個問題? – Pantss 2015-12-06 05:34:53

+3

「''指令的範圍僅適用於該目錄」 - 否則不適用。它適用於該目錄_and_下面的所有子目錄。所以''文件「log.txt」>'會抓住'/ log.txt' _and_'/inscription/log.txt'。 – MrWhite 2017-01-30 15:45:13

13

強大的模式匹配 - 這是我在這裏使用的易腐按方法。使用強模式匹配,此技術可防止外部訪問任何包含「.hta」,「.HTA」或其任何不區分大小寫的組合的文件。爲了說明這一點,這個代碼將阻止訪問通過以下任何請求:

  • 的.htaccess
  • 的.htaccess
  • 的.htaccess
  • testFILE.htaccess
  • filename.HTACCESS
  • FILEROOT。 hTaCcEsS

..等等。顯然,這種方法效果很好保護您網站的HTAccess文件。此外,該技術還包括強化「滿足所有」指令。請注意,此代碼應放置在您的域的根HTAccess文件中:

# STRONG HTACCESS PROTECTION 
<Files ~ "^.*\.([Hh][Tt][Aa])"> 
order allow,deny 
deny from all 
satisfy all 
</Files> 
+0

使用此代碼時,出現500內部服務器錯誤。任何想法爲什麼?我正在使用Wordpress。 – 2015-01-26 21:25:15

+3

禁止用戶訪問點文件是否更有意義?使用類似「'。 – 2016-11-15 09:12:22

7

我不相信目前接受的答案是正確的。例如,我有以下.htaccess文件在虛擬服務器的根(阿帕奇2.4):

<Files "reminder.php"> 
require all denied 
require host localhost 
require ip 127.0.0.1 
require ip xxx.yyy.zzz.aaa 
</Files> 

這防止了reminder.php外部訪問這是在一個子目錄中。 我有我的Apache 2.2的服務器上使用相同的效果類似的.htaccess文件:

<Files "reminder.php"> 
     Order Deny,Allow 
     Deny from all 
     Allow from localhost 
     Allow from 127.0.0.1 
    Allow from xxx.yyy.zzz.aaa 
</Files> 

我不知道肯定,但我懷疑這是在.htaccess文件中明確定義子目錄下的嘗試,<Files ./inscription/log.txt>這是導致它失敗。將.htaccess文件放在與log.txt相同的目錄中會比較簡單,在inscription目錄中,它將在那裏工作。

+0

你得到我的upvote,這也適用於我的apache 2.4。 – Tschallacka 2018-01-24 20:38:23

0

放置在.htaccess文件下面的行和替換文件名,如你所願

RewriteRule ^(test\.php) - [F,L,NC] 
-2

那麼你可以使用<Directory>標籤 例如:

<Directory /inscription> 
    <Files log.txt> 
    Order allow,deny 
    Deny from all 
    </Files> 
</Directory> 

不要使用./因爲如果您只是使用/它會查看您網站的根目錄。

對於更詳細的例子訪問http://httpd.apache.org/docs/2.2/sections.html

+1

但''.htaccess'中不允許有''容器。在'.htaccess'中,'.htaccess'文件本身就是「_Directory_容器」(每個目錄的配置文件)。 – MrWhite 2017-01-30 13:47:32

+0

那麼你可以使用重定向。 'Redirect /inscription/log.txt access_denied.html'如果用戶轉到銘文目錄中的「inscription/log.txt」,這會將用戶重定向到'access_denied.html'。 – 2017-01-30 14:47:01