Nginx - 将旧的 .php?id=... 重定向到 SEO 友好网址未按预期重定向

Nginx - 将旧的 .php?id=... 重定向到 SEO 友好网址未按预期重定向

我正在将具有旧式 /category.php?id=4 URL 的网站迁移到 /category/seo-friendly-slug URL。

rewrite ^/category.php?id=1$ /styles-de-bieres-belges/pils permanent;
rewrite ^/category.php?id=2$ /styles-de-bieres-belges/bieres-blanches permanent;
rewrite ^/category.php?id=4$ /styles-de-bieres-belges/lambics-et-gueuzes permanent;
rewrite ^/category.php?id=5$ /styles-de-bieres-belges/ales-stouts-et-ipa permanent;
rewrite ^/category.php?id=6$ /styles-de-bieres-belges/bieres-trappistes permanent;
rewrite ^/category.php?id=7$ /styles-de-bieres-belges/bieres-d-abbaye permanent;
rewrite ^/category.php?id=8$ /styles-de-bieres-belges/bieres-rouges-des-flandres permanent;
rewrite ^/category.php?id=9$ /styles-de-bieres-belges/lambics-et-gueuzes permanent;
rewrite ^/category.php?id=11$ /styles-de-bieres-belges/bieres-fruitees permanent;
rewrite ^/category.php$ /styles-de-bieres-belges permanent;

但所有'/category.php?id=...'请求都会重定向到/styles-de-bieres-belges(最后一行)。如果我删除最后一行,它根本不会重定向。

这个设置有什么问题?

答案1

停止使用这些 if 或一大堆具有类似匹配 URI 的重写。这样将更易于阅读和维护。这还可以避免性能下降,因为重写规则正则表达式是按顺序测试的。

用一个地图

map $arg_id $target {
    "1"  "pils";
    "2"  "bieres-blanches";
    "4"  "lambics-et-gueuzes";
    "5"  "ales-stouts-et-ipa";
    "6"  "bieres-trappistes";
    "7"  "bieres-d-abbaye";
    "8"  "bieres-rouges-des-flandres";
    "9"  "lambics-et-gueuzes";
    "11" "bieres-fruitees";
}

server {

    ...

    location /category {
        rewrite ^/category.php$ /styles-de-bieres-belges/$target? permanent;
    }

}

答案2

查询字符串在重写规则中被转换为变量,并被删除。对于您的示例,重写引擎看到的只是category.php,但存储了 的值$arg_id

尝试这样的操作:

location = /category.php {
if ($arg_id = "1") {rewrite ^ /styles-de-bieres-belges/pils permanent;}
if ($arg_id = "2") {rewrite ^ /styles-de-bieres-belges/bieres-blanches permanent;}

... the rest of them ...

if ($arg_id !~ "^\d+$") {rewrite ^ /styles-de-bieres-belges permanent;}
}

相关内容