【问题标题】:301 Redirect with correct slug使用正确的 slug 进行 301 重定向
【发布时间】:2015-09-16 20:11:07
【问题描述】:

重定向所有更改/重复的网址

/changed-title/2
/another-changed-title/2

更正网址

/original-correct-title/2

例如

http://stackoverflow.com/questions/232323/original-title-of-question

如果我更改 url (slug) 的最后一部分并按回车键

http://stackoverflow.com/questions/232323/changed-title-of-question-duplicate

仍会使用正确的 slug 重定向到正确的网址

在当前页面试试

我也想做同样的事

我正在使用 symfony 框架

routing.yml

topic_item_redirect:
    path:   /topic/{title}/{id}
    defaults: { _controller: AppBundle:Topic:redirectToItem }

topic_item:
    path:    /topic/{title}/{id}
    defaults: { _controller: AppBundle:Topic:item }

TopicController.php

public function redirectToItemAction($title,$id) {

    $title = $this->getDoctrine()->getManager()->getConnection()
        ->fetchColumn(
                'select title from topic where id = ?',
                [$id]);

    // action which renders topic
    return $this->redirectToRoute('topic_item',['title'=>$title,'id'=>$id],301);
}

这种方法不适合我

【问题讨论】:

    标签: php .htaccess symfony redirect


    【解决方案1】:

    要模拟 SO 行为,您可以在 TopicController.php 中添加这种 php sn-p:

    $id    = $_GET['id'];
    $title = $_GET['title'];
    
    $dbTitle = $this->getDoctrine()->getManager()->getConnection()
        ->fetchColumn(
                'select title from topic where id = ?',
                [$id]);
    
    if ($title != $dbTitle) {
       // redirect with 301 to correct /questions/<id>/<title> page
       header ('HTTP/1.1 301 Moved Permanently');
       header('Location: /questions/' . $id . '/' . $dbTitle);
       exit;
    }
    // rest of your script
    

    【讨论】:

      【解决方案2】:

      由于topic_item_redirect 和topic_item 使用相同的path 属性,您肯定会每次都被重定向。

      我认为您需要在控制器中处理此问题:获取 slug,查询 DB 并决定是否需要/不需要重定向。

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 2018-07-30
        • 1970-01-01
        • 2016-07-25
        • 1970-01-01
        • 2011-01-20
        • 2014-08-30
        • 2017-04-15
        • 2018-03-09
        • 2015-08-15
        相关资源
        最近更新 更多