2017-09-15 23 views
0

出於測試目的,我有我的網站的密碼保護克隆,可以使用子域名訪問,如dev.example.com。我正在使用basic authentication,所有流量應該使用https轉移。因此,在認證之前,使用http的任何請求必須重定向到https。我已經嘗試了以下.htaccess文件。爲什麼在使用L標誌進行身份驗證之前不會重定向?

RewriteEngine On 

# Rewrite any requests to ip addresses or *.example.com to dev.example.com 
RewriteCond %{HTTP_HOST} !^dev\.example\.com$ [NC] 
RewriteCond %{THE_REQUEST} \s(\S*)\s 
RewriteRule^https://dev.example.com%1 [L,NE,R=302] 

# Rewrite to https 
RewriteCond %{HTTPS} off 
RewriteCond %{HTTP:X-Forwarded-Proto} !https 
RewriteRule^https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302] 

# Require authentication 
AuthName "Restricted development environment" 
AuthType Basic 
AuthUserFile /var/www/html/.htpasswd 
Require valid-user 

我檢查都%{HTTPS}%{HTTP:X-Forwarded-Proto}同時支持在客戶端直接的情況下連接的服務器,也當服務器負載平衡器後面的情況下,負載均衡器之間的通信該服務器正在使用http

這個想法是,[L] flag應該導致重定向發生在身份驗證之前,但似乎並非如此。當訪問http://dev.example.com時,彈出認證。如果我正確輸入憑據,我將被重定向到https://dev.example.com,並且驗證會再次彈出。

我發現此類似question,其中[L]標誌未使用。建議的解決方案是在使用https時設置環境變量,並且只有在設置該變量時才允許訪問。但我不明白爲什麼我不能使用[L]標誌。也許我誤解了它的用途和意義。爲什麼在使用[L]標誌時在認證之前完成重定向?

+0

你誤會'L'標誌。 'L'標誌只起循環中的「continue」作用。它只是強制'mod_rewrite'循環再次運行。除了使用完全獨立於'L'標誌的'mod_auth_basic'完成驗證外。 – anubhava

+0

謝謝,@anubhava。從文檔:「使用此標誌來表明應該立即應用當前規則而不考慮其他規則。」對我來說,這聽起來像是一個302重定向應該在'[L,R = 302]'規則匹配時立即完成,並且直到重定向之後才能達到auth部分? –

+0

auth部分來自不同的模塊,因此'L'標誌或任何'mod_rewrite'標誌都不會阻止它執行。也可能發生auth節首先在'mod_rewrite'模塊之前執行。 – anubhava

回答

0

看來,不同的Apache模塊獨立工作,並且[L]標誌不防止發生認證,儘管文件稱Use this flag to indicate that the current rule should be applied immediately without considering further rules.

我結束了在If指令包裝認證檢查的連接安全。

如果連接不安全,則不執行認證,並且請求被重定向。重定向後,連接是安全的,並且執行認證。

# Require authentication 
# If the connection is not secure, authentication is postponed 
<If "%{HTTPS} = 'on' || %{HTTP:X-Forwarded-Proto} = 'https'"> 
    AuthName "Restricted development environment" 
    AuthType Basic 
    AuthUserFile /var/www/html/.htpasswd 
    Require valid-user 
</If> 
相關問題