【问题标题】:How to force a mod_rewrite RewriteRule to display as rewritten even if the un-rewritten url is entered即使输入了未重写的 url,如何强制 mod_rewrite RewriteRule 显示为已重写
【发布时间】:2011-03-15 14:52:42
【问题描述】:

是否可以强制重写 url?

这是一个有效的示例,http://localhost/home/ 转到 http://localhost/index.php?page=home,但 URL 对用户保持不变。

我无法开始工作是强制 http://localhost/index.php?page=home 显示为 http://localhost/home/.

我不知道我是否使用了正确的术语,但我希望这样,如果您键入未重写的 url,我希望重写的 url 出现在用户的浏览器中。

这是我到目前为止所做的工作:

RewriteEngine on
Options +FollowSymLinks

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond $1 !^(index\.php)
RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/?$ index.php?page=$1&a=$2&b=$3 [L,NC,QSA]

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond $1 !^(index\.php)
RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)$ index.php?page=$1&a=$2 [L,NC,QSA]

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond $1 !^(index\.php)
RewriteRule ^([a-zA-Z0-9_]*)$ index.php?page=$1 [L,NC,QSA]

【问题讨论】:

  • 您不能在不重新加载页面的情况下更改用户输入的 url。在这种情况下,我认为重写规则不会对您有所帮助。 (见stackoverflow.com/questions/824349/…
  • 我认为你理解错了:如果你仔细想想,你只是不希望用户直接访问index.php,对吧?只需执行 404 并在 404 中显示一些真正有效的链接。 Nice 404 有类似“你的意思是http://localhost/home/”的消息吗? ...

标签: php apache mod-rewrite url-rewriting rewrite


【解决方案1】:

这就是 [R] 标志的用途。如果您的重写工作正常,您需要在 RewriteRule 的末尾添加 [R] 到您的其他标志。

【讨论】:

  • 如果我输入“localhost/home”,[R] 不会变成“localhost/index.php?page=home”吗?如果是这样,这是相反的效果。当我在用户的浏览器中输入“localhost/index.php?page=home”时,我希望它变成“localhost/home”。我想要这个,以便我的链接无论是否启用 mod_rewrite 都能正常工作。 顺便说一句,我不知道为什么这条评论中我的链接后面有分号,忽略它们...
【解决方案2】:

尝试在 index.php 中添加一些代码。

查看$_SERVER['SCRIPT_URL'] 变量以获得答案。当您在浏览器中输入“localhost/index.php?page=home”时,SCRIPT_URL 应该等于 '/index.php'。如果输入“localhost/home”,SCRIPT_URL 应该等于“/home”。您可以在您的 PHP 脚本中对此进行检查并从那里进行适当的重定向。

【讨论】:

  • 至于 .htaccess 解决问题的方法,我还在寻找。
猜你喜欢
  • 2021-12-30
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
  • 2014-07-14
  • 2017-04-20
  • 1970-01-01
相关资源
最近更新 更多