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

如何在生产环境配置React代理中间件(Laravel+Apache后端)

生产环境代理实现方案(React + Laravel + Apache)

核心思路

开发环境的http-proxy-middleware仅作用于React开发服务器,生产环境必须依赖后端(Laravel或Apache)实现反向代理,同时通过代理隐藏真实API地址。


方案一:Laravel 实现反向代理(推荐,可灵活控制逻辑)

利用Laravel的路由和HTTP客户端转发请求,同时可添加鉴权、日志等自定义逻辑:

  1. 定义代理路由
    在routes/api.php中添加对应代理规则:
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;

// 对应开发环境的/api1代理
Route::any('/api1/{any?}', function (Request $request, $any = '') {
    $targetUrl = 'https://book.com/retrive-details/' . $any;
    
    // 完整转发请求的方法、参数、头信息
    $response = Http::withHeaders($request->headers->all())
        ->send($request->method(), $targetUrl, [
            'query' => $request->query(),
            'body' => $request->getContent(),
        ]);
    
    // 返回代理后的响应,保留状态码与头信息
    return response($response->body(), $response->status())
        ->withHeaders($response->headers()->all());
})->where('any', '.*');

// 对应开发环境的/api2代理
Route::any('/api2/{any?}', function (Request $request, $any = '') {
    $targetUrl = 'https://book.com/send-details/' . $any;
    
    $response = Http::withHeaders($request->headers->all())
        ->send($request->method(), $targetUrl, [
            'query' => $request->query(),
            'body' => $request->getContent(),
        ]);
    
    return response($response->body(), $response->status())
        ->withHeaders($response->headers()->all());
})->where('any', '.*');
  1. 前端代码调整
    生产环境下,前端API请求直接指向Laravel域名下的/api1、/api2路径,无需再配置前端代理。

方案二:Apache 直接配置反向代理(服务器层面实现)

如果不需要Laravel介入业务逻辑,可直接在Apache虚拟主机中配置代理规则:

  1. 启用必要模块
    确保Apache已启用mod_proxy和mod_proxy_http模块(以Ubuntu/Debian为例):
sudo a2enmod proxy proxy_http
sudo systemctl restart apache2
  1. 添加代理规则
    在你的Laravel站点VirtualHost配置中加入:
<VirtualHost *:443>
    # 原有配置(DocumentRoot、SSLCertificateFile等)
    
    # 代理/api1到目标地址
    ProxyPass /api1 https://book.com/retrive-details/
    ProxyPassReverse /api1 https://book.com/retrive-details/
    
    # 代理/api2到目标地址
    ProxyPass /api2 https://book.com/send-details/
    ProxyPassReverse /api2 https://book.com/send-details/
</VirtualHost>

保存后重启Apache:

sudo systemctl restart apache2

关于隐藏API信息的说明

  • 无法彻底隐藏请求负载/响应:浏览器必须发送请求才能获取数据,用户通过网络控制台总能看到代理后的请求地址、请求体和响应内容。代理仅能隐藏真实的第三方API域名,避免直接暴露后端服务地址。
  • 敏感数据处理:所有敏感逻辑需放在Laravel后端完成,前端仅传输和展示非敏感数据,避免敏感信息出现在请求或响应中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:33:07