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

Next.js应用子目录部署WordPress遇跳转及映射问题求助

解决Next.js反向代理WordPress路径后跳转及URL显示问题

一、调整Next.js Rewrites配置

把原有的fallback规则移到主rewrites数组,并添加转发头,确保WordPress识别实际请求域名:

async rewrites() {
  return [
    {
      source: "/community/:path*",
      destination: "https://wordblog.com/community/:path*",
      headers: {
        "X-Forwarded-Host": "example.com",
        "X-Forwarded-Proto": "https",
      },
    },
  ];
}

原fallback规则仅在Next.js无匹配路由时生效,移到主数组能保证优先代理/community路径的请求;添加X-Forwarded-Host头可避免WordPress因识别到原服务器域名而触发跳转。

二、修复WordPress的URL生成逻辑

现有配置存在URL替换方向错误、覆盖不全的问题,按以下步骤调整:

  1. 完善wp-config.php配置
    在现有配置基础上添加以下常量,强制静态资源和接口使用代理域名:
define('FORCE_SSL_ADMIN', true);
define('WP_CONTENT_URL', 'https://example.com/community/wp-content');
define('WP_PLUGIN_URL', 'https://example.com/community/wp-content/plugins');
define('WP_THEME_URL', 'https://example.com/community/wp-content/themes');
define('REST_URL', 'https://example.com/community/wp-json');
  1. 重写functions.php的URL替换逻辑
    原代码把代理域名替换回原域名是错误的,需反过来替换所有WordPress生成的URL,并覆盖更多场景:
remove_filter('template_redirect','redirect_canonical');

// 覆盖所有URL生成场景的过滤钩子
add_filter('the_permalink', 'replace_wp_domain');
add_filter('post_type_link', 'replace_wp_domain');
add_filter('page_link', 'replace_wp_domain');
add_filter('site_url', 'replace_wp_domain', 10, 3);
add_filter('home_url', 'replace_wp_domain', 10, 3);
add_filter('rest_url', 'replace_wp_domain');
add_filter('wp_get_attachment_url', 'replace_wp_domain');

function replace_wp_domain($url) {
    return str_replace('https://wordblog.com/community', 'https://example.com/community', $url);
}
  1. 优化.htaccess跨域配置
    缩小跨域允许范围并补充必要的请求头,提升安全性:
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "https://example.com"
    Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>

三、清除WordPress缓存

彻底清除WordPress内置缓存或第三方缓存插件的缓存,确保新配置立即生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:50:46