【问题标题】:Remove ?q= from url with htaccess使用 htaccess 从 url 中删除 ?q=
【发布时间】:2021-12-11 00:25:27
【问题描述】:

我想要这个:

https://example.com/something

从这里:

https://example.com/?q=something

我在stackoverflow上发现了很多类似的问题,但没有一个对我有用,所以请帮助我。

例如我试过这个:

RewriteEngine On
RewriteRule ^(.*) index\.php?q=$1

使用这个 php 代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Document</title>
  </head>
  <body>
    <?php echo $_GET['q'] ?>
  </body>
</html>

但它总是显示“index.php”

【问题讨论】:

  • 如果现有问题都没有提供解决方案(虽然它们应该提供,因为这是很常见的事情),请提出一个问题,详细描述您尝试过的内容以及您面临的问题.
  • @MarkusAO 例如我试过这个:RewriteEngine On RewriteRule ^(.*) index\.php?q=$1 但它总是返回“index.php”
  • 请用您尝试过的详细信息更新您的问题。
  • 听起来你在其他地方有不同的重写,它在 before 这个运行,所以 URL 被重写两次:/something -> /index.php , 然后/index.php -> /index.php?q=index.php 要测试该理论,请尝试创建一个称为其他名称的页面,例如test.php,并将您的规则更改为RewriteRule ^(.*) test\.php?q=$1
  • 您也可以尝试为重写模块启用日志记录,并将结果发布在您的问题中。 Instructions for Apache 2.4 are here,或者如果这些不起作用,请尝试 the version for 2.2 here

标签: php apache .htaccess mod-rewrite


【解决方案1】:
RewriteRule ^(.*) index\.php?q=$1

...但它总是显示“index.php”

这是因为相当通用的模式 ^(.*) 也匹配 index.php 并最终在重写引擎的第二次传递中将请求重写为 index.php?q=index.php(当在 目录 上下文中使用时,比如.htaccess)。

如果您的网址(如/something)不包含点,那么您可以简单地从正则表达式中排除点,这样它就不会匹配index.php。排除点还意味着它应该避免匹配任何静态资源(通常直接映射到以文件扩展名结尾的文件,这些文件自然由点分隔,例如image.jpgstyles.css 等)。

例如,请尝试以下操作:

RewriteRule ^([^.]*)$ index.php?q=$1 [L]

没有必要对 substitution 字符串(第二个参数)中的文字点进行反斜杠转义,因为这是一个“常规”字符串,而不是正则表达式,并且该点在这里没有特殊含义。

【讨论】:

  • 谢谢你!
猜你喜欢
  • 1970-01-01
  • 2021-10-02
  • 2015-01-20
  • 2013-05-09
  • 2023-03-07
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
相关资源
最近更新 更多