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

.htaccess file redirects to wrong destination

· 52CE 我爱测

I have a LAMP stack. I'm using the following .htaccess file to automatically map requests to .php files: RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.php [NC,L] So if I browse to http://example.com/asdf the "asdf…

问题原文

原帖链接 · Ryan Griggs · CC BY-SA 3.0

I have a LAMP stack. I'm using the following .htaccess file to automatically map requests to .php files:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

So if I browse to http://example.com/asdf the "asdf.php" file will be loaded.

However, if I create a .css file with the same name (i.e. "asdf.css"), then the server returns the css file instead of the PHP file when browsing to the name without extension. Also seems to happen for .txt file extensions, and probably any other three-character extension (although does NOT happen for .js files).

I can't understand why this is happening. My understanding of the rewrite ruleset is this: 1) if the file being requested doesn't exist THEN 2) if the filename does NOT contain a period, redirect the request to [filename].php

How can this ever return a .txt or .css file, especially when the matching .php file exists? What am I missing here?

Thanks!

已采纳解答

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

If you have multiple files with the same basename, then it sounds like you may have a conflict with MultiViews. Try disabling this in your .htaccess file (or server config):

Options -MultiViews

MultiViews (part of mod_negotiation) does the same sort of thing you are trying to do with mod_rewrite and I suspect is "winning". When you request /asdf and asdf maps to a file basename then MultiViews attempts to serve an appropriate file that would match the intended mime-type (which may explain why .js files get missed).

My understanding of the rewrite ruleset is this: 1) if the file being requested doesn't exist THEN 2) if the filename does NOT contain a period, redirect the request to [filename].php

Otherwise, your understanding of the mod_rewrite directives is pretty much correct, except the order is the other way round (the RewriteRule pattern is processed first)...

  1. If the URL (the entire URL that is) does not contain a period.
  2. And the request does not map to a valid file (unlikely if all your files have file extensions - so this condition could perhaps be omitted).
  3. Internally rewrite the request by appending a .php extension.
RewriteRule ^([^\.]+)$ $1.php [NC,L]

There's no need to escape a literal period in a character class, and the NC flag is superfluous here.

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

资料来源与适用范围

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

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

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