.htaccess的行为异常

cunj1qz1  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(108)

我有一个非常简单的php项目,包含三个文件,名为file.phpfile-success.phpfile-failure.php
根目录中有一个**.htaccess**文件,包含以下代码行:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^file-success file-success.php [NC,L]
RewriteRule ^file-failure file-failure.php [NC,L]
RewriteRule ^file file.php [NC,L]

令人惊讶的是,/file-success为我提供了file.php的内容。
但是,如果我切换第4行和第5行,/file-failure会给我file.php的内容。
这种行为的原因是什么?我错过了什么概念?

2fjabf4q

2fjabf4q1#

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^file-success file-success.php [NC,L]
RewriteRule ^file-failure file-failure.php [NC,L]
RewriteRule ^file file.php [NC,L]

当您请求/file-success时...
1.第一个规则将请求重写为file-success.php。重写引擎使用L标志重新启动。
1.第三个规则将file-success.php重写为file.php。正则表达式^file匹配任何以file开头的URL路径。
你需要在正则表达式中更具体一些。例如,包括字符串末尾的锚点。并且前面的 conditionsRewriteCond指令)对于这样一组有限的规则是不需要的(这些条件只适用于第一个规则)。
请改用下列程式码:

RewriteEngine On

RewriteRule ^file-success$ file-success.php [NC,L]
RewriteRule ^file-failure$ file-failure.php [NC,L]
RewriteRule ^file$ file.php [NC,L]

但是,您应该避免在这里使用NC标志,因为它可能会导致重复内容。这3个规则可以使用regex * alternate * 合并为一个规则,例如:

RewriteRule ^(file-success|file-failure|file)$ $1.php [L]

$1反向引用包含所请求的文件基名,由RewriteRule * 模式 * 捕获。

相关问题