【问题标题】:How can I redirect 404 to home in symfony?如何在 symfony 中将 404 重定向到主页?
【发布时间】:2016-01-21 12:10:44
【问题描述】:

我想重定向这个网址http://www.businessbid.ae/stagging/web/feedbackhttp://www.businessbid.ae。我能做什么?

【问题讨论】:

  • 我建议不要这样做,最好显示一个有意义的错误消息并发送 HTTP 404,而不是仅仅重定向到主页,这可能会让用户感到困惑期待内容或消息,解释为什么他们无法获取内容

标签: php symfony


【解决方案1】:

您应该创建一个侦听器来侦听onKernelExceptionEvent
您可以检查 404 状态代码并从中设置重定向响应。

AppBundle\EventListener\Redirect404ToHomepageListener

namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Routing\RouterInterface;

class Redirect404ToHomepageListener
{
    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * @var RouterInterface $router
     */
    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    /**
     * @var GetResponseForExceptionEvent $event
     * @return null
     */
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // If not a HttpNotFoundException ignore
        if (!$event->getException() instanceof NotFoundHttpException) {
            return;
        }

        // Create redirect response with url for the home page
        $response = new RedirectResponse($this->router->generate('home_page'));

        // Set the response to be processed
        $event->setResponse($response);
    }
}

services.yml

services:
    app.listener.redirect_404_to_homepage:
        class: AppBundle\EventListener\Redirect404ToHomepageListener
        arguments:
            - "@router"
        tags:
            - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

【讨论】:

  • 发现404时是否默认运行?
  • 每次出现异常时都会调用异常监听器。 NotFoundHttpException 是在没有匹配请求路径的路由时生成的。简而言之,是的。
  • 你在日志中得到了什么吗?你清除缓存了吗?是否正在加载事件侦听器(是否显示在 app/console debug:event-dispatcher kernel.exception 中)?
  • 那有帮助吗?还是我们就这样搁置了?
  • 令人震惊的是,“不!我还没有清除缓存”。从那以后您是否尝试过清除缓存?我上一个问题中的其他内容呢?
【解决方案2】:

您需要覆盖默认的Exception Controller。恕我直言,更好的解决方案是在 .htaccess 或 nginx 配置中完成这项工作。

【讨论】:

  • 你能分享任何例子吗?
  • 在配置部分查看这个 apache 文档here
【解决方案3】:

在你的控制器中试试这个:

$this->redirect($this->generateUrl('route_name')));

【讨论】:

  • 每次控制器没有响应时..它会自动重定向到主页!有可能吗?还有10多个控制器??
  • 这是第二个问题Varun
  • 试试这个 'public function indexAction(Request $request) { // 检查 $request 对象并重定向}'
  • 这种方法只有在你有回应的情况下才有效,这会破坏拥有它的目的。
猜你喜欢
  • 2021-08-09
  • 2021-11-03
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 2015-03-25
相关资源
最近更新 更多