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

Laravel 11+Inertia线上重定向报错:需有效Inertia响应(本地正常)

问题解决:Nginx反向代理下Inertia重定向报错

核心原因

线上Nginx反向代理环境中,普通redirect()->to()的响应在代理转发时丢失了Inertia请求上下文,或重定向地址配置(如APP_URL)与实际访问域名不匹配,导致Inertia无法识别重定向响应,触发All Inertia requests must receive a valid Inertia response, however a plain JSON response was received错误。

解决方案

1. 修正Nginx反向代理配置

确保Nginx传递所有必要请求头,且不修改重定向地址:

location / {
    proxy_pass http://your-laravel-app:8000; # 替换为你的Laravel服务地址
    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;
    proxy_set_header X-Inertia $http_x_inertia;
    proxy_redirect off; # 禁止Nginx自动修改重定向URL
}

2. 使用Inertia兼容的重定向方法

在路由中针对Inertia请求返回符合要求的响应,替代普通redirect():

use Illuminate\Http\Request;

Route::get('/redirected', function(Request $request) {
    // 针对Inertia请求返回带上下文的重定向
    if ($request->header('X-Inertia')) {
        return redirect()->to('/destination')->withInertia();
    }
    // 非Inertia请求走普通重定向
    return redirect()->to('/destination');
});

Route::get('/destination', function() {
    return Inertia::render('Example');
});

Laravel 11可直接简化为:

Route::get('/redirected', function() {
    return redirect()->to('/destination')->withInertia();
});

3. 配置正确的APP_URL

在.env文件中设置线上实际访问域名,确保重定向地址与用户访问地址一致:

APP_URL=https://your-production-domain.com

4. /admin路由的适配处理

针对/admin路由的登录判断,同样使用Inertia兼容重定向:

Route::get('/admin', function() {
    if (auth()->check()) {
        return redirect()->to('/admin/posts')->withInertia();
    }
    return redirect()->to('/login')->withInertia();
})->middleware('auth');

内容的提问来源于stack exchange,提问作者Mate Pušić

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:35:17