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

适配反向代理:如何将WordPress文章等链接设为相对链接?

实现WordPress反向代理下的链接处理方案

核心思路

通过WordPress钩子系统对输出链接做针对性过滤:

  • 保留/wp-content/开头的资源链接原域名
  • 将文章、页面、归档、作者等页面链接转换为仅含路径的相对格式

具体实现步骤

1. 添加链接过滤代码

将以下代码添加到当前主题的functions.php(或自定义插件,推荐后者避免主题更新丢失代码):

// 替换为你的原WordPress站点完整域名
define('ORIGINAL_WP_DOMAIN', 'https://www.wordpress.com');

// 统一处理链接的过滤函数
function filter_wp_links($url) {
    // 保留/wp-content/资源的原域名
    if (strpos($url, '/wp-content/') !== false) {
        return $url;
    }

    // 移除原域名,提取相对路径
    $relative_url = str_replace(ORIGINAL_WP_DOMAIN, '', $url);
    
    // 确保路径以/开头,避免相对路径错误
    if (substr($relative_url, 0, 1) !== '/') {
        $relative_url = '/' . $relative_url;
    }
    
    return $relative_url;
}

// 挂载到WordPress核心链接生成钩子
add_filter('home_url', 'filter_wp_links');
add_filter('site_url', 'filter_wp_links');
add_filter('the_permalink', 'filter_wp_links');
add_filter('post_type_link', 'filter_wp_links');
add_filter('term_link', 'filter_wp_links');
add_filter('author_link', 'filter_wp_links');

2. 配置反向代理服务器(以Nginx为例)

确保代理服务器传递正确请求头,让WordPress能识别真实请求路径:

location / {
    proxy_pass https://www.wordpress.com;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

3. 验证效果

完成配置后,访问代理站点并查看页面源代码:

  • 确认文章、页面等链接已转换为/path-to-post/格式
  • 确认/wp-content/下的CSS、JS、图片等资源仍保留原WordPress域名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:13:19