Apache-2.4

Htaccess Require expr Apache 2.4 適用於 osx-sierra 而不是 debian-jessie

  • February 1, 2018

在我的開發機器 osx-sierra / apache 2.4.10(來自 brew)上,我在 VirtualHost 中有一個限制,允許在沒有密碼的情況下訪問 /api/,所有其他頁面都需要使用以下程式碼的密碼:

<Location />
   AuthType Basic
   AuthName "Access"
   AuthUserFile /Users/xxxxxx/www/public/.htpasswd
   Require expr %{REQUEST_URI} =~ m#^/api/*#
   Require valid-user
</Location>

當我嘗試在生產伺服器上使用相同的指令 Debian-jessie / apache 2.4.29(來自 apt)時,它不起作用,總是詢問密碼(chrome/safari/wget),我嘗試了這些解決方案:

1/

<Location />
   AuthType Basic
   AuthName "Access"
   AuthUserFile /home/xxxxxx/www/public/.htpasswd
   Require expr %{REQUEST_URI} =~ m#^/api/*#
   Require valid-user
</Location>

2/

<Location />
   AuthType Basic
   AuthName "Access"
   AuthUserFile /home/xxxxxx/www/public/.htpasswd
   Require expr %{REQUEST_URI} =~ m#^/api/.*#
   Require valid-user
</Location>

知道為什麼會有這些差異嗎?

謝謝

這是指令不起作用的完整虛擬主機:

<VirtualHost *:80>
DocumentRoot /home/xxxxxx/www/public
ServerName xxxxxx.com

Header set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, PUT, GET, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "x-so-resource, x-so-apikey, x-so-apisecret, x-token, Authorization, Content-Type"

<Directory /home/xxxxxx/www/public>
   php_value include_path "/home/xxxxxx/libs/ZendFramework-1.11.11/library"
   Options +FollowSymLinks 
   AllowOverride All
   Order allow,deny
   Allow from all
   Require all granted
</Directory>

ServerSignature Off

AddDefaultCharset UTF-8

php_value short_open_tag 0

SetEnv APPLICATION_ENV development


<Location />
   RewriteEngine On     
   RewriteCond %{REQUEST_FILENAME} -s [OR]
   RewriteCond %{REQUEST_FILENAME} -l [OR]
   RewriteCond %{REQUEST_FILENAME} -d
   RewriteRule ^.*$ - [NC,L]
   RewriteRule ^.*$ index.php [NC,L]
</Location>


<LocationMatch "^(?!/api/.*$).*$">
   AuthType Basic
   AuthName "Access"
   AuthUserFile /home/xxxxxx/www/public/.htpasswd
   Require valid-user
</LocationMatch>

ErrorLog /var/log/apache2/xxxxxxxx-error.log
CustomLog /var/log/apache2/xxxxxxxx-access.log combined

我不確定為什麼這會在 osx-sierra / Apache 2.4.10 上工作,但在 Debian-jessie / Apache 2.4.29 上似乎不行。但是,作為一種解決方法,您可以使用容器上的負前瞻<LocationMatch>來執行此操作,而不是使用 Apache 2.4 表達式。例如:

<LocationMatch "^(?!/api/.*$).*$">
   AuthType Basic
   AuthName "Access"
   AuthUserFile /Users/xxxxxx/www/public/.htpasswd
   Require valid-user
</LocationMatch>

現在,容器內的指令<LocationMatch>僅在 URL 未啟動時處理/api/。(這也適用於 Apache 2.2)

引用自:https://serverfault.com/questions/894798