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

What does %{REQUEST_FILENAME}.ext mean? Why the extra .ext ending?

· 52CE 我爱测

The %{REQUEST_FILENAME} contains a string like this: /web/webroot/index.php I see a lot of people recommend testing if a file exists and has a .php extension like this: RewriteCond %{REQUEST_FILENAME}.php -f Isn't the .php after …

问题原文

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

The %{REQUEST_FILENAME} contains a string like this:

/web/webroot/index.php

I see a lot of people recommend testing if a file exists and has a .php extension like this:

RewriteCond %{REQUEST_FILENAME}.php -f

Isn't the .php after %{REQUEST_FILENAME} redundant? The variable should already contain the .php, right?

Seems like adding .php after %{REQUEST_FILENAME} would make the TestString check add an extra .php, like this:

/web/webroot/index.php.php

I'm missing something simple, I'm sure of it, but I just don't know what it is.

The context is this:

RewriteCond %{THE_REQUEST} ^.*?\.php [NC]
RewriteRule ^ - [R=404,NE,L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_FILENAME}.php [L]

已采纳解答

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

Isn't the .php after %{REQUEST_FILENAME} redundant? The variable should already contain the .php, right?

Well, yes and no, it depends what you are trying to do.

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_FILENAME}.php [L]

This rule allows you to request extensionless URLs. eg. /index or /foo and this internally rewrites the request to /index.php and /foo.php respectively.

In this instance, REQUEST_FILENAME is a string of the form /web/webroot/index. So, it's testing that /web/webroot/index.php exists before rewriting to the same. If you were to request /index.php then the condition fails and no rewrite occurs (which is correct).

However, this rule isn't strictly correct and could cause a rewrite-loop under certain conditions. See the following related question:

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

资料来源与适用范围

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

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

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