重写 url 变量包含斜杠转义的 %2F 时的状态标头 404



我创建了一个wordpress网站,通过将2个查询变量传递给具有我的自定义php模板的WP页面,动态显示大约40万种产品之一。我正在使用WPML来翻译我的页面,并且我已经启用了保持网址变量_brand和_sku的选项。使用此设置(页面显示和状态 200 ok 标题)一切正常。语言切换器还保留我的查询变量。

网址如下所示: domain.com/en/products/?_brand=JCB&_sku=01%2F117903

但是,由于我希望 URL 像 domain.com/en/products/a-brand/a-sku 一样显示,因此我在孩子的函数中添加了以下重写规则.php

function rewrite_products()
{
//en
add_rewrite_rule('^products/([^&]+)/([^&]+)', 'index.php?page_id=93837&_brand=$matches[1]&_sku=$matches[2]', 'top');
//nl
add_rewrite_rule('^producten/([^&]+)/([^&]+)', 'index.php?page_id=93871&_brand=$matches[1]&_sku=$matches[2]', 'top');
//fr
add_rewrite_rule('^produits/([^&]+)/([^&]+)', 'index.php?page_id=93875&_brand=$matches[1]&_sku=$matches[2]', 'top');
//de
add_rewrite_rule('^produkte/([^&]+)/([^&]+)', 'index.php?page_id=93876&_brand=$matches[1]&_sku=$matches[2]', 'top');
//es
add_rewrite_rule('^productos/([^&]+)/([^&]+)', 'index.php?page_id=93877&_brand=$matches[1]&_sku=$matches[2]', 'top');
}
add_action('init', 'rewrite_products');
function rewrite_product_tags()
{
add_rewrite_tag('%_brand%', '([^&]+)');
add_rewrite_tag('%_sku%', '([^&]+)');
}
add_action('init', 'rewrite_product_tags', 10, 0);

我现在可以浏览到所需的 URL,并且我得到了具有正确产品的相同页面,但是标题现在给出 404 作为状态。

WPML的语言切换器也会丢弃我的查询变量,只是将/products/a-brand/a-sku重定向到例如/producten(/products的翻译)。

但最重要的是,404 标题状态不允许我索引我在站点地图中转储的页面(大约 2M URL),因为 Google 认为该 URL 是 404 并且没有索引这些。相比之下,这是一个巨大的问题。

我将其归结为以下问题:

  • 我正在使用 rawurlencode 来更改 SKU 中的/等字符 至 %2F
  • 这会导致标头为 404
  • JCB/005549646Z/此网址完美(显示良好和良好的标题)
  • JCB/01%2F117903/显示正常,但具有 404 标头

在模板中设置标题不起作用。我的正则表达式错了吗?任何帮助不胜感激!

我猜错误与核心WordPress相关或在我的父主题中的某个地方。无论如何,我从未找到解决方案,只有一种解决方法,可以在字符串编码时将%2F替换为!2F

//Custom encoding en decoding to stop %2F 404 headers
function url_decode($encoded)
{
$encoded = str_replace('!2F', '%2F', $encoded);
$part_url = urldecode($encoded);
return $part_url;
}
function url_encode($part_url)
{
$encoded = rawurlencode($part_url);
$encoded = str_replace('%2F', '!2F', $encoded);
return $encoded;
}

最新更新