我想使用 htaccess 来允许访问索引文件以及目录中的一些其他文件 (index.php),但目录中的所有其他文件都需要用户/密码。现在我有:
AuthName "SomeServer"
AuthUserFile /path/to/.htpasswd
AuthGroupFile /dev/null
Require valid-user
AuthType Basic
<FilesMatch "(index.php)|(login.php)">
Allow from all
Satisfy any
</FilesMatch>
这允许用户访问 index.php 和 login.php,并拒绝访问目录的其余部分。但是,每当用户请求 URL 中不包含 index.php 的目录时,例如:
http://www.example.com/dir
系统会提示用户登录。但是,如果用户转到此处:
http://www.example.com/dir/index.php
然后会显示 index.php,但不会显示登录提示。
我需要做哪些更改才能允许用户访问http://www.example.com/dir并指向http://www.example.com/dir/index.php无需提示登录,但目录中的其他任何内容仍需要登录?
更新:不确定这是否重要,但我将身份验证切换为使用 mod_auth_mysql。仍然使用我的 htaccess 文件的同一部分,仍然面临同样的问题。
答案1
您可以尝试以下方法
<VirtualHost *:80>
ServerName localhost
DocumentRoot /vhosts/default
DirectoryIndex index.php
<Directory /vhosts/default>
Options -Indexes
AllowOverride All
Order allow,deny
Allow from all
</Directory>
<Location ~ ^/dir/(index|login)\.php$>
Allow from all
Satisfy any
</Location>
<Location ~ ^/dir/?$>
Allow from all
Satisfy any
</Location>
</VirtualHost>
进行一些基本测试
# curl -I http://localhost/
HTTP/1.1 401 Authorization Required
Date: Fri, 19 Feb 2016 10:03:38 GMT
Server: Apache/2.2.15 (CentOS)
WWW-Authenticate: Basic realm="SomeServer"
Content-Type: text/html; charset=iso-8859-1
# curl -I http://localhost/index.php
HTTP/1.1 401 Authorization Required
Date: Fri, 19 Feb 2016 10:03:43 GMT
Server: Apache/2.2.15 (CentOS)
WWW-Authenticate: Basic realm="SomeServer"
Content-Type: text/html; charset=iso-8859-1
# curl -I http://localhost/dir/index.php
HTTP/1.1 200 OK
Date: Fri, 19 Feb 2016 10:03:49 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.6.16
Content-Type: text/html; charset=UTF-8
# curl -I http://localhost/dir/
HTTP/1.1 200 OK
Date: Fri, 19 Feb 2016 10:03:52 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.6.16
Content-Type: text/html; charset=UTF-8
# curl -I http://localhost/dir/some_file.php
HTTP/1.1 401 Authorization Required
Date: Fri, 19 Feb 2016 10:04:07 GMT
Server: Apache/2.2.15 (CentOS)
WWW-Authenticate: Basic realm="SomeServer"
Content-Type: text/html; charset=iso-8859-1
# curl -I http://localhost/dir
HTTP/1.1 301 Moved Permanently
Date: Fri, 19 Feb 2016 10:04:14 GMT
Server: Apache/2.2.15 (CentOS)
Location: http://localhost/dir/
Content-Type: text/html; charset=iso-8859-1