apache - .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>
解决方案
你想的太复杂了。保持简单:
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 服务器主机配置(阅读:非常便宜的服务提供商)或坚持编写自己的规则的应用程序(这是一个明显的安全噩梦)的情况下作为最后一个选项提供。
推荐阅读
- javascript - 如何在开玩笑的测试之间恢复模拟实现?
- javascript - 是否可以列出组件依赖注入器的数组?
- xaml - 按钮按下状态忽略 CornerRadius 设置
- azure - Azure 流分析转换数组值
- azure - Spark 集群 OutOfMemoryError 需要更多内存
- angular - 你将如何创建一个页面来实时更新 10 个人的数据?
- c# - 在 Nest ElasticSearch 中对计数和搜索重用查询
- android - Endless RecyclerView,到最后重复数据
- mysql - mariadb/mysql - 如何使用 sysdate/curdate 创建日期列?
- r - 在 SQLite 中使用子查询更新表