【问题标题】:How to send a 410 gone in cakephp 2.x如何在 cakephp 2.x 中发送 410 消失
【发布时间】:2015-08-08 10:15:13
【问题描述】:

我希望服务器对我在 CakePHP 中未发布的旧 URL 的响应为 410。

CakePHP 提供了各种异常,例如 404、500 等,但没有像 410 这样的异常。

如果有人打开网站上不再存在但曾经存在的旧 URL,我有什么办法可以服务器 410 消失响应。

谢谢,

【问题讨论】:

    标签: php cakephp http-response-codes


    【解决方案1】:

    首选方法是抛出异常。扩展 HttpException 的异常。您还可以从此类扩展并创建自己的自定义异常。

    https://github.com/cakephp/cakephp/blob/3.0.11/src/Network/Exception/BadRequestException.php

    <?php
    
    use Cake\Network\Exception\HttpException;
    
    class GoneException extends HttpException
    {
        /**
         * Constructor
         *
         * @param string $message If no message is given 'Gone' will be the message
         * @param int $code Status code, defaults to 410
         */
        public function __construct($message = null, $code = 410)
        {
            if (empty($message)) {
                $message = 'Gone';
            }
            parent::__construct($message, $code);
        }
    }
    

    【讨论】:

    • 为您提供帮助。我覆盖了解决此问题的“AppExceptionRenderer”。请在我的回答中查看详细信息。
    【解决方案2】:

    我做了以下解决这个问题。

    我在“AppExceptionRenderer”中添加了“gone”功能

    public function gone($error) {
    
            $this->controller->layout = 'nopageexists';
    
            $this->controller->set('title_for_layout', __('example.com: Page not found'));
            $this->controller->set('meta_description', '' );
            $this->controller->set('meta_keywords', '');
    
            // This will execute 404 Error Page without redirection added by vinod...
            $this->controller->response->statusCode(410);
            $this->controller->render('/Errors/error404');
            $this->controller->response->send();
        }
    

    在 app/Lib/myException.php 中创建了一个自定义类

    class GoneException extends CakeException {
    
    /**
     * Constructor
     *
     * @param string $message If no message is given 'Not Found' will be the message
     * @param integer $code Status code, defaults to 410
      */
        /*
        public function __construct($message = null, $code = 410) {
            if (empty($message)) {
                $message = 'Gone';
            }
            parent::__construct($message, $code);
        }
        */
        protected $_messageTemplate = 'Test';
    }
    

    在我想显示 410 消失的 Controller 中添加。

    throw new GoneException('Gone', 410);
    

    这对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      相关资源
      最近更新 更多