一个项目中用到百度地图,加密要求较高,全站使用 HTTPS,但百度地图API至今不支持HTTPS。无奈只好自己整……于是做了个简易反向代理,所有百度地图的流量走服务器,对所有百度api 的页面URL作替换,确保引用脚本走服务器。很简单的代码,效果也不错,不过用户多了可能服务器的负担会较大。
public function proxyAction(Request $request, $url)
{
$content = file_get_contents($url . '?' . $request->getQueryString());
$response = new Response();
foreach ($http_response_header as $value)
{
if (preg_match('/^Content-Type:(.*)/i', $value, $matches)) {
$type = $matches[1];
$response->headers->set('Content-Type', $type);
if (preg_match('/javascript/i', $type)) {
//一些不是百度服务器的地址不要替换。为方便起见,只屏蔽了w3.org 的替换,其实应该用白名单……
$content = preg_replace('@(http://)(?!www\.w3\.org)@', '/proxy/$1', $content);
}
}
}
$response->setContent($content);
return $response;
}
相关的 route 是这样的:
path: /proxy/{url}
defaults: { _controller: "EmfoxXXXXBundle:Default:proxy" }
requirements:
url: .+
请注意 url 的 requirement 必须加,默认的 route 参数是不允许“/”的
最后,在引用百度API的页面中这样用:
<script src="/proxy/http://api.map.baidu.com/api?v=2.0&ak=YOURBAIDUAPIKEY" type="text/javascript">
没有评论:
发表评论