网站首页 laravel框架
Laravel--NGINX-反向代理后根域名生成
发布时间:2019-06-21 02:24查看次数:4404
需求描述:
用户需要顶级域名 绑定程序的子域名 比如 www.1.com 绑定到360.game.2.com上
通过以下NGINX反向代理设置
location /{
proxy_pass http://www.1.com; #反向代理到拥有全部客户信息的上游地址
proxy_redirect off;
proxy_set_header Host $proxy_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Proxy $host; #将请求地址发送给上游
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
把 www.1.com 全部转到360.game.2.com上
问题:
这个时候,代理是通的 但是laravel 框架的特性 用url() 快捷方法生成地址 都变成 http://360.game2.com 上
而不是 www.1.com 上~~经过一天的折腾 解决办法有三个写法
解决:
1.修改源码 url()
添加如下代码 vendor\laravel\framework\src\Illuminate\Routing\RoutingServiceProvider.php protected function registerUrlGenerator() { $this->app->singleton('url', function ($app) { $routes = $app['router']->getRoutes(); // The URL generator needs the route collection that exists on the router. // Keep in mind this is an object, so we're passing by references here // and all the registered routes will be available to the generator. $app->instance('routes', $routes); $url = new UrlGenerator( $routes, $app->rebinding( 'request', $this->requestRebinder() ) ); $url->setSessionResolver(function () { return $this->app['session']; }); // If the route collection is "rebound", for example, when the routes stay // cached for the application, we will need to rebind the routes on the // URL generator instance so it has the latest version of the routes. $app->rebinding('routes', function ($app, $routes) { $app['url']->setRoutes($routes); }); //添加的代码部分 就是如果使用了上层代理 就用上层代理的域名 $reques = $url->getRequest(); $proxy = $reques->header("x_proxy"); if ($proxy != null){ $url->forceRootUrl("http://".$proxy); } return $url; }); }
2.添加一个自定义的全局帮助方法MyUrl()
if (! function_exists('MyUrl')) {
/**
* Generate a url for the application.
*
* @param string $path
* @param mixed $parameters
* @param bool $secure
* @return \Illuminate\Contracts\Routing\UrlGenerator|string
*/
function MyUrl($path = null, $parameters = [], $secure = null ,$root = null)
{
if (is_null($path)) {
return app(UrlGenerator::class);
}
$app_url = app(UrlGenerator::class);
if (!is_null($root)){
$app_url->forceRootUrl($root);
}
return $app_url->to($path, $parameters, $secure);
}
}
个人推荐方法
3.调用
$url = MyUrl("test",null,null,"http://www.2.com");
dd($url);
public function index(Request $request){
使用代理过来是上层路由
$proxy = $request->header("x_proxy");
$url = MyUrl("test",null,null,$proxy);
dd($url);
// dd($temp,$host,$proxy);
}
现在生成的URL 就是你域名带过来的
关键字词:laravel##