停止对受保护目录中的文件进行 .htaccess 重写

Stop .htaccess rewriting for files in protected directory

简而言之,这是常规的 TYPO3 RealURL .htaccess,位于 public_html:

# * BASIC TYPO3 URL REWRITING *
# -----------------------------
RewriteRule ^typo3$ - [L]
RewriteRule ^typo3/.*$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php

它会将不是以 typo3 开头的不是文件、目录或符号链接的传入链接重定向到中央入口点 index.php。

现在我们有一个名为 public/user_upload/myDir.

的 .htaccess/httpauth 受保护目录

其 .htaccess 文件仅包含以下几行:

AuthUserFile "/home/user/.htpasswds/public_html/fileadmin/user_upload/myDir/passwd"
AuthType Basic
AuthName "Please authenticate"
require valid-user

只要启用了主 .htaccess 重定向,就不可能从该目录访问文件 www.mysite.com/public/user_upload/myDir/myfile.pdf

没有显示 httpauth-login-dialogue,这是期望的结果,index.php 的 RewriteRule 仍然适用。

所以我想从重写中排除该目录,方法是添加以下行:

# * BASIC TYPO3 URL REWRITING *
# -----------------------------
RewriteRule ^typo3$ - [L]
RewriteRule ^typo3/.*$ - [L]
// stop rewriting if myDir is accessed
RewriteRule ^public/user_upload/myDir/.*$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php

听起来不错,但行不通。重写仍然转到 index.php。 可能是什么原因?

好像!-d 无法检测到目录。也许是因为它受到保护?

我意识到我的问题实际上是关于 mod_rewrite 和 htpasswd 之间的冲突。谷歌搜索这些术语,我发现 https://www.drupal.org/node/33645, leading to https://serverfault.com/questions/55323/disable-mod-rewrite-for-subdirectory and http://www.myriadinteractive.com/blog/view/id/29/conflict-between-apache-url-rewriting-and-basic-authentication

For basic authentication, the server writes a "401 Unauthorized" header and then looks for an error document based on a pre-defined path. Most of the time, the error document won't exist in the directory that you want to protect, so the request gets handled by the rewrite engine which throws a 404 error.

解决方法很简单:return 一个 401 并关闭受保护目录中的 mod_rewrite。

所以每个 .htaccess 文件都必须这样编辑:

# new
ErrorDocument 401 "Unauthorized Access"
RewriteEngine off

# as before
AuthType Basic
AuthName "MyName"
AuthUserFile "/home/mysite/.htpasswds/public_html/my/path/"
require valid-user