【问题标题】:Handling HTTP 303 redirects in zf2在 zf2 中处理 HTTP 303 重定向
【发布时间】:2014-12-02 04:35:51
【问题描述】:

我正在 zend 框架 2 中构建一个小型 CMS 系统。我的新网站将有一个新的 url 结构,我想创建 303 错误处理程序。

理想的解决方案:

如果没有找到页面,用户或搜索引擎将通过旧 url 访问网站,如果找到 url,它将检查存储在(db 或数组)中的旧 url 列表,如果找到它将创建 303 重定向。如果在列表中没有找到 url,它应该创建 404 页面。

网址示例:

旧的(不存在的)网址:www.example.com/category/product123.html 这应该被重定向到新的网址:www.example.com/category/product-name/

总共有 100 多个旧页面需要重定向到新 url。

我应该如何正确地做到这一点?

【问题讨论】:

    标签: php http zend-framework2 request response


    【解决方案1】:

    HTTP 303 是自定义重定向标头,不是错误,应该在 HTTP POST 之后使用。如果您想要保留一些旧版网址(出于 SEO 目的等),您可以考虑使用 HTTP 301 - Moved Permanently 标头。

    Http Serverapplication 级别中,有多种方法可以将任何 HTTP 请求重定向到任何其他资源。我更喜欢 nginx/apache 级别。以 Nginx 为例:

    server {
    
      # ...
    
      location ~ "^/category/([a-zA-Z0-9]+).html" {
          # Example: http://www.example.com/category/product123.html
          # The $1 will be product123 
          return 303 http://www.example.com/category/$1;
      }
    
      # ...
    
    }
    

    现在,在重新加载您的 http 服务器配置后调用旧的 /category/product123.html url 将产生类似这样的响应:

    HTTP/1.1 303 See Other
    Server: nginx/1.X.0
    Date: Tue, 07 Oct 2014 20:47:29 GMT
    Content-Type: text/html; charset=UTF-8
    Content-Length: 168
    Connection: keep-alive
    Location: http://www.example.com/category/prodct123
    

    在应用程序级别,您可以轻松地重定向由有效Response 对象返回的任何控制器操作内的请求:

    public function anyControllerAction()
    {
        $response = $this->getResponse();
        $response->getHeaders()->addHeaderLine('Location', 'http://www.example.com/category/prodct123');
        $response->setStatusCode(303);
        return $response;
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2015-06-10
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 2011-11-01
      • 2015-06-23
      相关资源
      最近更新 更多