apache - 我的 mod_rewrite 出了什么问题?

标签 apache .htaccess mod-rewrite

我在我的网站上设置了一个简单的 mod_rewrite 系统,它基本上可以进行转换

http://site.com/file -> http://site.com/file.php

这是 .htaccess 文件

Options -MultiViews
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.site.com
RewriteRule ^(.*)$ http://site.com/$1 [R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z]+)/?$ http://site.com/$1.php [L]

这已经工作了很长一段时间,然后几天前我意识到,虽然 RewriteRule 正在工作,但它实际上正在更改状态栏中我的 URL。

例如,它会将/photos 重定向到/photos.php,但它也会更改 URL 以显示 .php。这种情况以前从未发生过,我不确定发生了什么触发了更改。

有什么想法吗?

最佳答案

第一个重写规则需要 [L] 标志。来自 [R] flag 的 mod_rewrite 文档:

You will almost always want to use [R] in conjunction with [L] (that is, use [R,L]) because on its own, the [R] flag prepends http://thishost[:thisport] to the URI, but then passes this on to the next rule in the ruleset, which can often result in 'Invalid URI in request' warnings.

在这种情况下,您不会收到警告,但附加“.php”扩展名会在发出重定向之前发生,而不是在第二个重定向请求传入时发生。

此外,从第二条重写规则的替换中删除方案和域名。完整的 URL 可能会导致隐式重定向。来自 RewriteRule 的文档:

The Substitution of a rewrite rule is the string that replaces the original URL-path that was matched by Pattern. The Substitution may be a:

[...]
Absolute URL
If an absolute URL is specified, mod_rewrite checks to see whether the hostname matches the current host. If it does, the scheme and hostname are stripped out and the resulting path is treated as a URL-path. Otherwise, an external redirect is performed for the given URL. To force an external redirect back to the current host, see the [R] flag below.

关于apache - 我的 mod_rewrite 出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7314745/

相关文章:

.htaccess : if is an path, 什么都不做,否则,做重写规则

.htaccess - 谁能想到子请求重写何时有用?

php - 为什么 $_GET = index.php

php - 如何阻止 Alexa 工具栏用户?

java - 为 Log4J2 + Apache HttpClient 启用调试日志记录

ruby-on-rails - Apache设置多个站点

wordpress - 在 Wordpress 中通过 HTTPS 加载 CSS 和 JS

php - 如何使用 PHP/apache 访问原始 HTTP 请求数据?

apache - 如何限制/控制 Apache Jmeter 中的采样率?

php - 将所有请求重定向到公共(public)文件夹中的index.php文件