提问人:Thomas Cottis 提问时间:9/22/2023 最后编辑:Don't PanicThomas Cottis 更新时间:9/23/2023 访问量:37
带有 GET 参数的 Apache 重写不起作用
Apache rewrite with GET parameters not working
问:
我有一个网址: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 错误
答:
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
评论
RewriteRule ^products\.php\?category=([^&]+)$ products/$1
%1
RewriteCond
/products/my-category
products.php
/products.php?category=my-category