带有 GET 参数的 Apache 重写不起作用

Apache rewrite with GET parameters not working

提问人:Thomas Cottis 提问时间:9/22/2023 最后编辑:Don't PanicThomas Cottis 更新时间:9/23/2023 访问量:37

问:

我有一个网址:www.example.com/products.php?category=category 我想重写 www.example.com/products/category

(类别可以是肉类、调味品或吸烟者,具体取决于用户希望看到的产品)

我使用了一些重写规则,这些规则在堆栈溢出和其他来源中看到过,但没有运气。

我最接近的是页面加载,但 category 参数返回 null 而不是值。

例如:

RewriteRule ^products/([^/]+)$ products.php?category=$1 [L,QSA]

将加载页面 www.example.com/products/meats,但服务器仅从类别查询中接收 null。

也试过这个:

# Check if the request is for /products.php with a category query parameter 
RewriteCond %{REQUEST_URI} ^/products\.php$ 
RewriteCond %{QUERY_STRING} ^category=meats$ 
# If the conditions are met, rewrite to /products/<category> with the query string 
RewriteRule ^products\.php$ /products/%1 [L,QSA] 

只是两个页面都出现 404 错误

正则表达式 apache url mod-rewrite url-重写

评论

0赞 Thomas Cottis 9/22/2023
也试过这个: # 使用类别查询参数 RewriteCond %{REQUEST_URI} 检查请求是否针对 /products.php ^/products\.php$ RewriteCond %{QUERY_STRING} ^category=meats$ # 如果满足条件,则使用查询字符串 RewriteRule 重写到 /products/<category> ^products\.php$ /products/%1 [L,QSA] 两个页面都出现 404 错误
0赞 Nahuel Fouilleul 9/22/2023
不应该是吗?RewriteRule ^products\.php\?category=([^&]+)$ products/$1
0赞 Don't Panic 9/22/2023
but the server only receives null from the category query” 是什么意思?您的第一个重写规则看起来是正确的,如果页面加载,则表明它有效。那么你的PHP在做什么呢?您的第二个示例走错了路,从您当前的 URL 格式重定向到不存在的 URL。也用于匹配 中的第一个反向引用,但您在这里没有。httpd.apache.org/docs/2.4/mod/mod_rewrite.html%1RewriteCond
0赞 Patrick Janser 9/22/2023
这对我来说不是很清楚,因为您的第一个 RewriteRule 是处理 URL,例如使用名为 .是这样吗?或者您是否有旧的已发布 URL 指向,并且您想将它们重写为干净的 URL,例如,使用另一种技术运行的新网站?您的 Apache 虚拟主机是否充当反向代理?/products/my-categoryproducts.php/products.php?category=my-category
1赞 Don't Panic 9/22/2023
@PatrickJanser 问题的第一句话解释了当前的情况和要求。这似乎是经典的“漂亮的 URL”要求。

答:

0赞 Patrick Janser 9/22/2023 #1

正如@DontPanic所说,你的第一个 RewriteRule 是正确的。我继续 我的Apache安装,它适用于以下配置。

内容.htaccess

RewriteEngine On
RewriteBase /

RewriteRule ^products/([^/]+)$ products.php?category=$1 [L,QSA]

顺便说一句,如果您在之前添加可选的前导斜杠 获得相同的行为:products

RewriteRule ^/?products/([^/]+)$ products.php?category=$1 [L,QSA]

内容products.php

<?php

header('Content-Type: text/plain; charset=utf-8');

print $_SERVER['PHP_SELF'] . "\n";

print '$_GET = ' . var_export($_GET, true) . ";\n";

这是我的浏览器输出的:http://rewrites.local/products/smoky-stuff

/products.php
$_GET = array (
  'category' => 'smoky-stuff',
);

关于 404 错误的一些想法:

  • 您是否验证了服务器上是否启用了mod_rewrite

  • 如何为此网站 (VirtualHost) 设置 AllowOverride? 是否允许覆盖 FileInfo? 它实际上为您提供了在文件中执行 RewriteRules 的可能性,因此您需要 像这样的东西:.htaccess

    <VirtualHost *:80> 
        DocumentRoot "/var/www/rewrites.local"
        ServerName rewrites.local
        <Directory "/var/www/rewrites.local">
            AllowOverride All
            Require all granted
        </Directory>
    </VirtualHost>
    

    或者至少允许 FileInfo

    AllowOverride FileInfo