You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为博客文章永久链接添加'/blog/'并实现旧URL重定向求助

为文章类URL添加/blog/前缀并实现旧URL重定向

一、WordPress 解决方案

1. 配置新永久链接结构

进入后台「设置」→「永久链接」,选择「自定义结构」,输入:
/blog/%postname%/
此设置会让所有文章的新URL自动带上/blog/前缀,页面、分类等其他类型内容不受影响。

2. 旧URL重定向实现

方法1:通过主题代码实现

在主题的functions.php文件末尾添加以下代码:

function redirect_old_post_urls() {
    global $wp;
    // 仅针对文章类型,且当前URL不含/blog/前缀时触发重定向
    if (is_singular('post') && strpos($wp->request, 'blog') === false) {
        $new_url = home_url('/blog/' . $wp->request . '/');
        wp_redirect($new_url, 301);
        exit;
    }
}
add_action('template_redirect', 'redirect_old_post_urls');

方法2:通过.htaccess配置实现

在WordPress默认的重写规则之前,添加以下规则:

RewriteEngine On
# 匹配不含/blog/的文章URL,重定向到带/blog/的地址
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ /blog/$1/ [R=301,L]

二、Hexo 解决方案

1. 配置新永久链接结构

在站点根目录的_config.yml中修改permalink字段:

permalink: blog/:title/

设置后,所有文章会生成带/blog/前缀的URL,页面(page)类内容默认保留原有URL结构。

2. 旧URL重定向实现

安装hexo-plugin-redirect插件:

npm install hexo-plugin-redirect --save

然后在_config.yml中添加全局重定向规则:

redirect:
  rules:
    - from: /:title/
      to: /blog/:title/

三、Jekyll 解决方案

1. 配置新永久链接结构

在_config.yml中修改永久链接规则:

permalink: /blog/:title/

2. 旧URL重定向实现

在站点根目录创建_redirects文件,添加以下规则:

/:title/    /blog/:title/    301

如果是GitHub Pages托管,该文件会自动生效;其他托管环境可配合服务器配置实现。

四、通用服务器端重定向配置

Nginx 配置

在站点的server配置块中添加:

# 匹配不含/blog/的旧文章URL,重定向到新地址
rewrite ^/([^/]+)/$ /blog/$1/ permanent;

若存在静态文件或页面URL冲突,可添加条件限制匹配范围,比如仅针对文章存储目录的URL。

Apache 配置

在.htaccess文件中添加:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/blog/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /blog/$1 [R=301,L]

内容的提问来源于stack exchange,提问作者yuvin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:12:57