在zf2中处理HTTP 303重定向

时间:2014-10-07 16:58:51

标签: php http zend-framework2 request response

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

理想的解决方案:

如果找不到页面,用户或搜索引擎将通过旧网址访问该网站,如果网址发现它将创建303重定向,它将检查存储在(数据库或数组)中的旧网址列表。如果在列表中找不到URL,则应创建404页面。

网址示例:

旧的(没有退出)网址:www.example.com/category/product123.html这应该重定向到新的网址:www.example.com/category/product-name /

总的来说,我将有超过100个旧页面需要重定向到新网址。

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

1 个答案:

答案 0 :(得分:1)

HTTP 303是自定义重定向标头,不是错误,应在HTTP POST后使用。如果保留一些遗留URL是你想要的(出于搜索引擎优化等目的......),你可以考虑使用HTTP 301 - Moved Permanently标题。

有几种方法可以将任何HTTP请求重定向到 Http Server application 级别中的任何其他资源。我更喜欢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;
}

希望它有所帮助。