如何将一个特定的URL重写为404,但允许另一个重写的URL访问同一个URL



我的服务器上有一个特定的文件(让我们将此文件称为file-handler),它应该处理对具有特定扩展名的文件的所有请求。然而,file-handler本身不应该是可直接访问的。

我尝试过的:

  • file-handler放在受密码保护的目录中。不幸的是,任何重写到该特定目录的URL都会导致浏览器(因此服务器)请求密码,因此这种方法不起作用
  • 将对file-handler的直接访问重写为默认的404页面,不幸的是,任何重写为file-handler的URL都会导致mod_Rewrite为404页面提供服务

第二次尝试的来源:

RewriteBase /
RewriteRule dontallowdirectaccess.xxx$ - [R=404,L]
#Only serve existing files to the file-handler
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .ext$ dontallowdirectaccess.xxx [QSA,L]

对于第一个404强制执行规则,请使用THE_REQUEST变量。THE_REQUEST变量表示Apache从浏览器收到的原始请求,并且REQUEST_URI变量不同,它在执行某些重写规则后不会被覆盖

RewriteCond %{THE_REQUEST} /dontallowdirectaccess.xxx[?s/] [NC]
RewriteRule ^ - [R=404,L]
#Only serve existing files to the file-handler
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .ext$ dontallowdirectaccess.xxx [L]

所以我发现他们实际上是另一种方法,不需要解析{THE_REQUEST}变量。

#Only serve existing files to the file-handler (directories not included)
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule (^.+.ext$) dontallowdirectaccess.xxx?file=$1 [QSA,L]
#If ENV:REDIRECT_STATUS is empty than someone must be trying to access the file directly.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule dontallowdirectaccess.xxx$ - [R=404,L]

最新更新