2

以下适用于允许在两个 XML 文件上执行 PHP:

<FilesMatch ^(opensearch|sitemap)\.xml$>
AddHandler application/x-httpd-php5 .xml
</FilesMatch>

然而不幸的是,这条规则也允许在任何子目录中发生这种情况。

  • /opensearch.xml,工作/期望的匹配
  • /henchman24/opensearch.xml,工作/想要的匹配

我们如何强制 Apache匹配当前目录中的文件而不匹配子目录?

我真的很想:

  • 避免.htaccess在每个可能的子目录中添加子文件。
  • 避免使用绝对服务器路径。
4

2 回答 2

1

If指令可用于为仅添加与当前文件夹中的模式匹配的文件的处理程序提供条件。

以下示例将只为文档根目录中的文件添加处理程序,例如/sitemap.xmland/opensearch.xml但不为/folder/sitemap.xmland/folder/opensearch.xml

<FilesMatch ^(opensearch|sitemap)\.xml$>
<If "%{REQUEST_URI} =~ m#^\/(opensearch|sitemap)\.xml$#">
  AddHandler application/x-httpd-php .xml
</If>
</FilesMatch>

在上面的示例中,条件是检查REQUEST_URI匹配的正则表达式模式分隔在m# #. ~= 比较运算符检查字符串是否与正则表达式匹配。

模式^\/(opensearch|sitemap)\.xml$匹配REQUEST_URI变量 (请求的 URI 的路径组件),例如/opensearch.xml/sitemap.xml

^                      # startwith
\/                     # escaped forward-slash
(opensearch|sitemap)   # "opensearch" or "sitemap"
\.                     # .
xml                    # xml
$                      # endwith
于 2020-04-10T15:27:55.463 回答
0

您是否在 RewriteRule 中尝试过 H=?

RewriteEngine On
RewriteRule ^(opensearch|sitemap)\.xml$ . [H=application/x-httpd-php5]

htaccess 中的重写具有内置属性,即任何子目录中的那些文件名都将在正则表达式测试的字符串中存在子目录,因此锚定的正则表达式在子目录中将不匹配。

于 2020-04-12T01:04:27.793 回答