You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware 6.5:404页面跳转首页/搜索页失败求助

问题原因分析

你在Twig模板中尝试跳转的方式存在核心问题:

  • HTTP跳转要求响应头必须在任何HTML内容输出前发送,但你修改的模板已经开始渲染页眉(输出了HTML内容),之后调用app.close()发送跳转头时,浏览器已经收到了部分HTML,无法触发跳转。
  • app.close()没有中断模板的渲染流程,所以页眉和页脚仍会被输出,导致你看到空白内容区+简化页眉的现象。
解决方案

方案1:使用Shopware事件订阅(推荐,符合官方扩展规范)

通过监听异常事件,在404异常触发时直接返回跳转响应,完全跳过错误页模板渲染:

  1. 创建事件订阅类
<?php

namespace YourPluginNamespace\Subscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class Error404RedirectSubscriber implements EventSubscriberInterface
{
    private $urlGenerator;

    public function __construct(UrlGeneratorInterface $urlGenerator)
    {
        $this->urlGenerator = $urlGenerator;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::EXCEPTION => 'onKernelException',
        ];
    }

    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $event->getThrowable();
        // 判定是否为404异常
        if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
            // 跳转首页,如需跳转搜索页,替换路由为`frontend.search.page`
            $redirectUrl = $this->urlGenerator->generate('frontend.home.page');
            // 永久跳转用301,临时跳转用302,根据需求选择
            $response = new RedirectResponse($redirectUrl, 301);
            $event->setResponse($response);
        }
    }
}
  1. 在插件的src/Resources/config/services.xml中注册订阅
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="YourPluginNamespace\Subscriber\Error404RedirectSubscriber">
            <argument type="service" id="router"/>
            <tag name="kernel.event_subscriber"/>
        </service>
    </services>
</container>

方案2:模板修改(仅临时测试用,不推荐)

如果一定要通过模板实现,需要完全替换error-404.html.twig内容,避免继承父模板(防止页眉页脚输出):

{% set redirectUrl = path('frontend.home.page') %}
{% do app.response.setTargetUrl(redirectUrl) %}
{% do app.response.setStatusCode(302) %}
{% do app.close() %}

这种方式稳定性差,不符合Shopware扩展最佳实践,仅适合临时验证。

内容的提问来源于stack exchange,提问作者Codixio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 22:13:26