AI摘要

本文提供了Typecho修改永久链接后实现旧链接301跳转的教程,包括适用的链接路径和代码示例。通过在Typecho的config.inc.php文件中插入代码,可以实现从旧链接到新链接的301重定向,以保持搜索引擎收录。同时,文章还介绍了如何在百度资源平台提交改版规则,以帮助百度识别文章迁移。

前言

本文仅用于开启typecho地址重写且适合本站主题(HandSome)跳转路径的情况下。

在建站时,因认为 /{文章分类}/{文章ID}.html 的文章路径好看。所以一直都没有去修改过,导致被百度收录久了之后又想改文章路径怕百度的收录全掉了,现在带来 301跳转 的教程,让百度认为文章只是迁移到了新的地方而不是删除了文章。(记得去提交 百度改版哦)

代码

适用路径:website.com/{category}/{cid}.html

适用路径:website.com/{category}/{cid}.html/comment-page-{评论页}

适用路径:website.com/{cid}.html

适用路径:website.com/{cid}.html/comment-page-{评论页}


跳转路径:website.com/{cid}.html

跳转路径:website.com/{cid}.html/comment-page-{评论页}#comments

跳转路径:website.com/archives/{cid}.html

跳转路径:website.com/archives/{cid}.html/comment-page-{评论页}#comments

打开 Typecho 下的 config.inc.php 文件,在 require_once 'Typecho/Router.php'; 前面的位置插入以下代码,如果没有则放到合适的位置

  • 适用于 {category}/{cid}.html 跳转到 {cid}.html
/**
 * 旧链接 301跳转 新链接
 * 适用于 {category}/{cid}.html 跳转到 {cid}.html
 */

$host = $_SERVER['HTTP_HOST'];  // 获取当前主机域
$requestUri = $_SERVER['REQUEST_URI']; // 获取当前请求URI

// 分离路径和查询字符串
$urlParts = parse_url($requestUri);
$path = $urlParts['path'] ?? '';
$query = isset($urlParts['query']) ? '?' . $urlParts['query'] : '';

// 优化后的正则表达式(匹配 {category}/{cid}.html 格式)
$pattern = '/^\/([\w-]+)\/(\d+)\.html(\/comment-page-(\d+))?\/?$/i';

if (preg_match($pattern, $path, $matches)) {
    // 构建新URL路径 - 直接使用文章ID
    $newPath = '/' . $matches[2] . '.html';
  
    // 保留评论分页片段(如果存在)
    if (isset($matches[3]) && $matches[3]) {
        $newPath .= $matches[3] . '#comments';
    }
  
    // 添加查询字符串
    $newUrl = $newPath . $query;
  
    // 自动检测当前协议
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
  
    // 执行301重定向
    header('HTTP/1.1 301 Moved Permanently');
    header("Location: $protocol://$host$newUrl");
    exit; // 确保重定向后停止执行
}
  • 适用于 {cid}.html 跳转到 archives/{cid}.html
/**
 * 旧链接 301跳转 新链接
 * 适用于 {cid}.html 跳转到 archives/{cid}.html
 */

// 获取当前请求信息
$host = $_SERVER['HTTP_HOST'];
$requestUri = $_SERVER['REQUEST_URI'];

// 分离路径和查询字符串
$parsedUrl = parse_url($requestUri);
$path = $parsedUrl['path'] ?? '';
$query = isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : '';

// 匹配 {cid}.html 格式的URL
$pattern = '/^\/(\d+)\.html(\/comment-page-\d+)?\/?$/';

if (preg_match($pattern, $path, $matches)) {
    $cid = $matches[1];
    $newUrl = "/archives/{$cid}.html";

    // 处理评论分页
    if (isset($matches[2])) {
        $newUrl .= $matches[2];
    }

    $newUrl .= $query;

    // 添加评论锚点
    if (isset($matches[2])) {
        $newUrl .= "#comments";
    }

    // 执行301重定向
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    header('HTTP/1.1 301 Moved Permanently');
    header("Location: $protocol://$host$newUrl");
    exit;
}

保存此次修改后,访问之前的链接即可跳转到新的地址啦!~如果有什么不明白的欢迎评论。

百度改版

打开 https://ziyuan.baidu.com/rewrite/,点击添加 改版规则>规则改版 填入以下内容(推荐尽量填写百度有收录的链接哦)

教程:平台工具使用手册\_网站改版\_搜索学堂\_百度搜索资源平台

最后修改:2025 年 09 月 26 日
如果觉得我的文章对你有用,请随意赞赏