使用 htaccess 从 url 中删除 ?q=

Remove ?q= from url with htaccess

我想要这个:

https://example.com/something

来自这里:

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

我在 Whosebug 上发现了很多类似的问题,但是 none 对我有用,所以请帮助我。

例如我试过这个:

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

使用此 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”

RewriteRule ^(.*) index\.php?q=

...but it's always shows "index.php"

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

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

例如,请尝试以下操作:

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

不需要反斜杠转义替换字符串(第二个参数)中的文字点,因为这是一个“常规”字符串,而不是正则表达式,并且点带有此处无特殊含义。