大网数据广告活动
服务器运维问答

Denying access to all files except index.php but allow access through "/" in htaccess file

· 52CE 我爱测

When I try limiting file access to just index.php using something similar to the answer in the link below I am unable to access through the directory index such as "DIRECTORY/" and "DIRECTORY". I want to be able to do the below a…

问题原文

原帖链接 · Damien Golding · CC BY-SA 4.0

When I try limiting file access to just index.php using something similar to the answer in the link below I am unable to access through the directory index such as "DIRECTORY/" and "DIRECTORY".

I want to be able to do the below and deny all files except index.php from a .htaccess file in DIRECTORY.

Denying access to all files except index.html apache

DIRECTORY/index.php?get1=val1  
DIRECTORY/?get1=val1  
DIRECTORY?get1=val1

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

To allow mod_dir to make the internal subrequest for the DirectoryIndex when requesting the bare directory, you just need to make the file match optional, so it also matches an essentially empty filename.

For example:

Order allow,deny
Deny from all
<FilesMatch ^(index\.php)?$>
  Allow from all
</FilesMatch>

This then allows both

  • DIRECTORY/index.php?get1=val1
  • and DIRECTORY/?get1=val1

Where DIRECTORY is any directory (including the document root).

However, this does not permit DIRECTORY?get1=val1 (no slash after the directory name). Strictly speaking, this is an invalid URL on Apache. Ordinarily, mod_dir "fixes" the URL by issuing a 301 redirect to append the trailing slash. ie. DIRECTORY?get1=val1 is externally redirected to DIRECTORY/?get1=val1. Unfortunately, the authorisation directives above block mod_dir from making this redirect.


If you specifically wanted to allow DIRECTORY?get1=val1 (no trailing slash) as well then you could instead do everything with mod_rewrite instead of mod_authz_host (Apache 2.2). For example, replace the above with the following:

RewriteEngine On
RewriteRule ^DIRECTORY/(?!index\.php|$) - [F]

This blocks access to the contents of the specific DIRECTORY, but allows /DIRECTORY/index.php and /DIRECTORY/ to be accessed. This doesn't do anything special with a request for /DIRECTORY (no trailing slash), but executes sufficiently late in the request for mod_dir to step in first and issue the 301 redirect (mentioned above).

(?!index\.php|$) is a negative lookahead - which is successful when index.php or $ (end of URL) does not match. ie. It matches everything except index.php and nothing.


Reference:

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-10-23)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。