首页 > 解决方案 > .htaccess 只会重定向而不重写

问题描述

我想将 example.com/foo 重写为 example.com/index.php?bar (PHP codeigniter)。

所有文件都在同一个域中。

作为起点并证明设置,以下代码成功重定向:

RewriteCond %{HTTPS} on
RewriteRule ^foo/$ https://example.com/index.php?bar [L,QSA,NC]

但我想重写而不是重定向。我一直无法弄清楚如何做到这一点。我为 RewriteRule 尝试了以下方法:

#These don't work
RewriteRule ^foo1/$ index.php?/bar [L,QSA,NC]
RewriteRule ^foo2/$ /index.php?/bar [L,QSA,NC]
RewriteRule ^foo3/$ index.php?/bar [L,QSA,NC,P]
RewriteRule ^foo4/$ /index.php?/bar [L,QSA,NC,P]
RewriteRule ^foo5/$ index.php?/bar [L,QSA,NC,PT]
RewriteRule ^foo6/$ /index.php?/bar [L,QSA,NC,PT]
RewriteRule ^foo7/$ https://example.com/index.php?/bar [L,QSA,NC,PT]

完整的 .htaccess 在这里:

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


RewriteCond %{HTTPS} on
RewriteRule ^foo/$ https://example.com/index.php?/bar [L,QSA,NC]    #works but redirects
RewriteRule ^foo1/$ index.php?/bar [L,QSA,NC]
RewriteRule ^foo2/$ /index.php?/bar [L,QSA,NC]
RewriteRule ^foo3/$ index.php?/bar [L,QSA,NC,P]
RewriteRule ^foo4/$ /index.php?/bar [L,QSA,NC,P]
RewriteRule ^foo5/$ index.php?/bar [L,QSA,NC,PT]
RewriteRule ^foo6/$ /index.php?/bar [L,QSA,NC,PT]
RewriteRule ^foo7/$ https://example.com/index.php?/bar [L,QSA,NC,PT]
</IfModule>

标签: apachecodeigniter-3.htaccess

解决方案


你想的太复杂了。保持简单:

RewriteEngine On

RewriteCond %{HTTPS} !on
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,QSA]

RewriteRule ^/?foo/?$ /bar [END]

应该首先完成从 http 到 http 的重定向,独立于内部重写。你需要把它分开。

此规则同样适用于 http 服务器主机配置或动态配置文件(“.htaccess”文件)。显然重写模块需要在http服务器内部加载并在http主机中启用。如果您使用动态配置文件,您需要注意它的解释在主机配置中完全启用,并且它位于主机的DOCUMENT_ROOT文件夹中。

如果您使用上述规则收到内部服务器错误(http 状态 500),那么您很可能操作的是非常旧版本的 apache http 服务器。[END]在这种情况下,您将在您的 http 服务器错误日志文件中看到明确提示不支持的标志。您可以尝试升级或使用较旧的[L]标志,在这种情况下它可能会起作用,尽管这取决于您的设置。

和一个一般性评论:您应该始终更喜欢将此类规则放在 http 服务器主机配置中,而不是使用动态配置文件(“.htaccess”)。这些动态配置文件增加了复杂性,通常是意外行为的原因,难以调试,而且它们确实减慢了 http 服务器的速度。它们仅在您无法访问真正的 http 服务器主机配置(阅读:非常便宜的服务提供商)或坚持编写自己的规则的应用程序(这是一个明显的安全噩梦)的情况下作为最后一个选项提供。


推荐阅读