2011-03-09 267 views
5

我想使用.htaccess密碼保護特定的網址。不同的網址指向相同的文件,但有不同的工作。我現在需要密碼保護只有一個網址。我試圖使用setenvif來做到這一點,但它似乎並沒有工作。我可能不完全瞭解apache setenv模塊的用途或用途。如何做條件.htaccess密碼保護

這是我的代碼似乎是什麼不工作

SetEnvIfNoCase Host "topasswordprotect\.domain\.com$" protecturl 
<IfDefine protecturl> 
    Require valid-user 
    AuthName "Please enter your name and password" 
    AuthType Basic 
    AuthUserFile .htpasswd 
</IfDefine> 
+1

相關問題:[有條件地要求HTTP認證取決於apache env變量](http://stackoverflow.com/q/5845353/195835)* – 2016-09-23 04:08:38

回答

3

我終於明白了。我確實必須使用mod_rewrite引擎。我決定有一個解決方案,不需要我製作額外的文件或目錄。

相同的文件,沒有多餘的目錄,一個的.htaccess:

# Case we are in the protected area! 
RewriteCond %{REQUEST_FILENAME} index.php [OR] 
RewriteCond %{REQUEST_FILENAME} !-f [OR] 
RewriteCond %{REQUEST_URI} ^(\/){1}$ 
RewriteCond %{REQUEST_FILENAME} !-d [OR] 
RewriteCond %{REQUEST_URI} ^(\/){1}$ 
RewriteCond %{HTTP_HOST} ^(protected)\.mydomain\.com$ 
RewriteRule ^(.*)$ admin.php%{REQUEST_URI} [L] 

#default rewrite 
RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ index.php/$1 [L] 

#only protect access to admin.php which is a symlink to index.php 
<FilesMatch "admin.php"> 
    AuthUserFile .htpasswd 
    AuthName EnterPassword 
    AuthType Basic 
    require valid-user 
</FilesMatch> 
+0

嗨,你密碼訪問文件在這裏,但如何你可以密碼保護一個博客,不物理上存在... com/blogname /但重定向使用htacess和永久鏈接? – 2011-04-21 09:54:47

+0

由於您將所有/ blogname重寫爲使用file.php和secure file.php,因此受保護!它工作得很好! – Clooner 2013-08-26 20:58:38

0

也許不能直接直接可能的,但你可以有裏面有原目錄鏈接到它的另一個密碼保護的目錄?您可以使用mod_rewrite將匹配的請求重定向到受密碼保護的目錄。

RewriteEngine on 
RewriteCond %{HTTP_HOST} ^www.myhost.tld$ 
RewriteRule ^/foo/(.*)$ /bar/linkeddir/$1 
3

那麼,這實際上可以不用mod_rewrite的,並與SetEnvIf實現。 我需要它爲dev網站測試Facebook OpenGraph標籤的工作方式。

# allow facebook external hit 
SetEnvIf user-agent "facebookexternalhit/1.1" allowthis 
# disallow some other stuff 
SetEnvIfNoCase Host "topasswordprotect\.domain\.com$" !allowthis 

AuthType Basic 
AuthName "dev access" 
AuthUserFile .htpasswd 
Require valid-user 

Allow from allowthis=1 
Satisfy Any 

IfDefine的作用是定義哪些與環境變量不相同。

甲引自apache docs

參數名稱參數是一個限定經由-Dparameter- httpd的命令行上給出,在所述服務器處開始的時間。