无sudo权限通过Apache public_html转发内部NodeJS API到公网方案咨询
无sudo权限下通过PHP反向代理暴露内部NodeJS服务方案
通用PHP全路由转发脚本
你可以直接使用下方PHP脚本实现全路由自动转发,无需硬编码任何API路径,支持所有HTTP请求方法、请求头/请求体透传、静态资源转发,完全不需要管理员权限,仅需将脚本放在你的public_html目录下即可使用。
<?php // 配置内部NodeJS服务的本地地址 $backendBase = 'http://localhost:4040'; // 处理请求路径:如果将脚本放在public_html根目录,直接使用以下代码 $requestPath = $_SERVER['REQUEST_URI']; // 如果将脚本放在public_html的api子目录下,请取消注释下方代码,并将studentid替换为你的学生账号ID // $requestPath = preg_replace('/^\/~studentid\/api/', '', $_SERVER['REQUEST_URI']); $targetUrl = $backendBase . $requestPath; $ch = curl_init($targetUrl); // 透传请求方法 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']); // 透传请求体 $postData = file_get_contents('php://input'); if ($postData) { curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); } // 透传请求头(跳过Host头避免冲突) $headers = []; foreach (getallheaders() as $name => $val) { if (strtolower($name) !== 'host') { $headers[] = sprintf("%s: %s", $name, $val); } } curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // 配置响应返回规则 curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $response = curl_exec($ch); $headerLength = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $respHeaders = substr($response, 0, $headerLength); $respBody = substr($response, $headerLength); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // 输出响应头,跳过无关的传输头 foreach (explode("\r\n", $respHeaders) as $headerLine) { $trimmedLine = trim($headerLine); if (empty($trimmedLine)) continue; $lowerLine = strtolower($trimmedLine); if (str_starts_with($lowerLine, 'transfer-encoding') || str_starts_with($lowerLine, 'connection')) continue; header($trimmedLine); } // 返回正确的HTTP状态码 http_response_code($httpCode); // 输出响应内容 echo $respBody; ?>
部署使用步骤
- 将上述代码保存为
index.php,上传到public_html目录,如果你需要区分静态资源和API,也可以在public_html下新建api文件夹,将脚本放在该文件夹内 - 保持你的NodeJS服务在服务器本地4040端口正常运行
- 公网访问
http://mi-linux.wlv.ac.uk/~studentid/你的路由即可等价访问内部的http://localhost:4040/你的路由,如果放在api子目录下则访问http://mi-linux.wlv.ac.uk/~studentid/api/你的路由
额外配置说明
- 如需支持跨域请求,可在脚本开头添加如下配置:
header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS"); header("Access-Control-Allow-Headers: *"); // 处理OPTIONS预检请求 if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { http_response_code(200); exit; } - 如需处理大文件或者长耗时请求,可在脚本开头添加
set_time_limit(0);取消PHP执行时间限制 - 静态资源如图片、JS、CSS文件都会被原样透传返回,无需额外配置
内容的提问来源于stack exchange,提问作者Just Mohit
相关产品推荐
相关产品推荐

