【问题标题】:mod_rewrite not working with query string without file extensionmod_rewrite 不适用于没有文件扩展名的查询字符串
【发布时间】:2021-05-14 10:01:03
【问题描述】:

我正在尝试将 user/John-Doe 重写为 user?name=John-Doe 并在 .htaccess 中使用 mod_rewrite。我的 .htaccess 与我正在重写/重定向的文件位于同一目录中。这是 htaccess:

中的代码
RewriteEngine on 
RewriteRule ^user/(\w+)/?$ user?name=$1

现在我没有收到来自 $_GET['name'] 的任何数据并且 var_dump($_GET) 是空的。

【问题讨论】:

  • \w 不匹配连字符,你需要[\w-]
  • 您的文件中是否还有其他规则,或者只有这个?请确认一次。
  • user 是能够运行 PHP 的脚本吗?不应该是user.php?name=$1吗?
  • @WiktorStribiżew 感谢它在本地服务器上工作,但是一旦我将它上传到我的虚拟主机,每个都会出现 404 错误
  • @RavinderSingh13 还有其他规则但不在此文件中。

标签: php regex .htaccess mod-rewrite


【解决方案1】:

您需要使用[\w-]+捕获更多字符
另外,您将请求指向user?name=$1,应该是user.php?name=$1

.htaccess

<IfModule mod_rewrite.c> # Check if mod_rewrite if avaible
    RewriteEngine on 
    RewriteRule ^user/([\w-]+)/?$ user.php?name=$1
</IfModule>

user.php

<?php
var_dump($_GET);
array(1) { ["name"]=> string(8) "John-Doe" }

测试示例

https://regex101.com/r/up32vA/1


还要检查你的服务器是否启用了mod_rewrite,一个简单的方法是把它放在index.php中

print_r( apache_get_modules() );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多