【问题标题】:Rewrite rules for redirect URLs using .htaccess使用 .htaccess 重写重定向 URL 的规则
【发布时间】:2023-03-18 18:16:01
【问题描述】:

我正在使用.htaccess 重定向我网站上的 URL,以避免出现诸如 page1.php 之类的链接。

我在根域上有一个子文件夹engine/index.php,我打算用它来处理重定向的 URL。

例如,我希望链接 localhost/user 重写为 localhost/engine/index.php?view=user 注意:正在使用的链接,即 /user 不是域中存在的文件或文件夹

【问题讨论】:

  • 到目前为止,您是否尝试过编写任何规则?

标签: php apache .htaccess mod-rewrite redirect


【解决方案1】:

使用这个:

RewriteEngine On

RewriteRule ^([a-z]+)$ engine/index.php?view=$1 [NC,L,QSA]

把它放在你的.htaccess 文件中,直接放在你的www/ 目录中。
([a-z]+) 将匹配一组字母(也是大写字母,因为使用了NC 标志),但如果不是a localhost/后面的字母不会被重写。如果localhost后面只有字母,则url会重写为engine/index.php?view=$1

L 标志表示这是最后一个 RewriteRuleQSA 标志将旧查询字符串附加到新查询字符串。例如:localhost/user?var=val 将重定向到 localhost/engine/index.php?view=user&var=val

但是,如果用户转到localhost/user?view=somethingelse,它将被重写为localhost/engine/index.php?view=user&view=somethingelse,这意味着如果你在engine.php中执行$_GET['view']会返回"别的东西”。要从查询字符串 (user) 中获取第一个 view 参数,请在 PHP 中使用此正则表达式:

$view = preg_replace('/view=([^&]+).*/', '$1', $_SERVER['QUERY_STRING']); //now, $view contains 'user'

【讨论】:

  • 做到了。谢谢@乔南。
  • 我正在使用 RewriteRule ^(.*)$ /engine/index.php?p=$1 [L,QSA]。不知道为什么它不起作用。
  • @jmsiox 可能是因为/engine/index.php?p=$1 前面的/。另请参阅我的更新答案,了解如何防止用户手动设置 view 参数
  • @T.J.Crowder 现在好点了吗? ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多