php 实现转发
PHP 实现 HTTP 转发
使用 PHP 的 cURL 扩展可以轻松实现 HTTP 请求转发。以下是一个基本示例,将接收到的请求转发到另一个目标 URL:

<?php
$targetUrl = 'https://example.com/api'; // 目标转发地址
$ch = curl_init($targetUrl);
// 设置转发方法(GET/POST等)
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
// 转发请求头
$headers = [];
foreach (getallheaders() as $name => $value) {
$headers[] = "$name: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 转发请求体(POST数据)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$postData = file_get_contents('php://input');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
// 返回响应
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 设置响应头并输出
header('Content-Type: ' . curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
http_response_code($httpCode);
echo $response;
curl_close($ch);
?>
PHP 实现 URL 重定向
对于简单的 URL 重定向,可以使用 header() 函数:

<?php
header('Location: https://example.com/new-page');
exit; // 确保重定向后停止执行后续代码
?>
使用 .htaccess 实现转发
对于 Apache 服务器,可以通过 .htaccess 文件实现 URL 转发:
RewriteEngine On
RewriteRule ^old-path$ /new-path [R=301,L]
使用 PHP 实现反向代理
更复杂的反向代理实现可以处理各种 HTTP 方法和头部:
<?php
$proxyUrl = 'https://backend-server.com';
$requestUri = $_SERVER['REQUEST_URI'];
$requestMethod = $_SERVER['REQUEST_METHOD'];
$ch = curl_init($proxyUrl . $requestUri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestMethod);
// 转发所有头部
$headers = [];
foreach (getallheaders() as $name => $value) {
if (strtolower($name) !== 'host') { // 排除Host头
$headers[] = "$name: $value";
}
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 处理请求体
if (in_array($requestMethod, ['POST', 'PUT', 'PATCH'])) {
$requestBody = file_get_contents('php://input');
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
header("Content-Type: $contentType");
http_response_code($httpCode);
echo $response;
curl_close($ch);
?>
注意事项
- 转发敏感数据时确保使用 HTTPS
- 考虑添加身份验证机制防止滥用
- 对于高流量场景,建议使用专业的反向代理如 Nginx
- 注意处理 CORS 头部如果需要跨域转发
- 考虑添加超时设置避免长时间等待
以上方法可以根据具体需求进行调整和组合,实现不同复杂度的转发功能。






