WooCommerce部分商品URL被加下划线致404错误求助
问题:部分WooCommerce商品URL末尾自动添加下划线导致404
部分商品访问时,URL末尾会被自动添加下划线,触发404错误,该问题具有一致性(同一商品要么始终添加,要么不添加),且与wp_posts表的GUID或post_name字段无关——无论是通过URL还是Post ID访问都会出现异常。
示例:
Bad index.php?page_id=1075707 the-john-rutter-christmas-piano-album-2 https://website-name.com/product/the-john-rutter-christmas-piano-album-2/ Good index.php?page_id=1087442 the-john-rutter-piano-album https://website-name.com/product/the-john-rutter-piano-album/ Bad index.php?page_id=1159681 parable-for-harpsichord https://website-name.com/product/parable-for-harpsichord/ Good index.php?page_id=1159684 jesu-meine-freude-2 https://website-name.com/product/jesu-meine-freude-2/
异常URL形式(Bad):
https://website-name.com/product/parable-for-harpsichord_/
已排查步骤:
- 禁用除WooCommerce外的所有插件,问题依旧
- 禁用
functions.php自定义代码,问题依旧 - 直接复制URL、手动输入、通过Post ID访问,均触发异常
解决思路:
1. 检查并刷新固定链接规则
- 进入WordPress后台「设置」→「固定链接」,确认WooCommerce产品固定链接结构无异常(比如是否存在多余的占位符或自定义规则)
- 先切换到任意默认固定链接结构并保存,再切回原有结构保存,强制刷新WordPress重写规则缓存
2. 排查数据库post_meta表的异常字段
针对异常商品ID,查询wp_postmeta表,检查是否存在与商品slug/permalink相关的异常自定义字段:
- 执行SQL查询筛选可能的异常项:
SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE meta_value LIKE '%_%' AND (meta_key LIKE '%slug%' OR meta_key LIKE '%permalink%') - 重点检查
_wp_old_slug等字段,是否存在带下划线的历史slug导致重定向冲突
3. 检查服务器端URL重写配置
- Apache环境:检查站点根目录的
.htaccess文件,对比WooCommerce官方默认重写规则,确认无篡改或异常规则 - Nginx环境:检查站点Nginx配置中的rewrite规则,排查是否有正则表达式错误导致URL末尾被添加下划线
4. 重新安装WooCommerce核心文件
备份站点后,在WordPress后台「插件」→「已安装插件」中,对WooCommerce执行「重新安装」操作,覆盖可能被篡改或损坏的核心文件
5. 排查批量导入遗留问题
如果异常商品是通过批量导入创建的,检查原始导入文件是否存在隐藏下划线或特殊字符,以及导入工具的规则是否导致slug被异常修改
6. 临时应急修复(代码方案)
如果需要快速缓解问题,可以添加以下代码到主题的functions.php(或自定义插件):
- 拦截产品URL生成,移除末尾下划线:
add_filter('post_type_link', 'fix_product_url_underscore', 10, 2); function fix_product_url_underscore($url, $post) { if ($post->post_type === 'product') { return rtrim($url, '_/') . '/'; } return $url; } - 对带下划线的404请求做301重定向:
add_action('template_redirect', 'redirect_underscore_product_url'); function redirect_underscore_product_url() { if (is_404() && strpos($_SERVER['REQUEST_URI'], '/product/') !== false && substr($_SERVER['REQUEST_URI'], -2) == '_/') { $correct_url = substr($_SERVER['REQUEST_URI'], 0, -2) . '/'; wp_redirect($correct_url, 301); exit; } }
内容的提问来源于stack exchange,提问作者RobPL
相关产品推荐
相关产品推荐

