Laravel routes behind reverse proxy

馋奶兔 提交于 2019-11-28 07:01:59
TimeLord

I ran into the same (or similar problem), when a Laravel 5 application was not aware of being behind an SSL load-balancer.

I have the following design:

  • client talks to an SSL load balancer over HTTPS
  • SSL load balancer talks to a back-end server over HTTP

That, however, causes all the URLs in the HTML code to be generated with http:// schema.

The following is a quick'n'dirty workaround to make this work, including the schema (http vs. https):

Place the following code on top of app/Http/routes.php

$proxy_url    = getenv('PROXY_URL');
$proxy_schema = getenv('PROXY_SCHEMA');

if (!empty($proxy_url)) {
   URL::forceRootUrl($proxy_url);
}

if (!empty($proxy_schema)) {
   URL::forceSchema($proxy_schema);
}

then add the following line into .env file:

PROXY_URL = http://igateway.somedomain.com

If you also need to change schema in the generated HTML code from http:// to https://, just add the following line as well:

PROXY_SCHEMA = https

In latest version of laravel forceSchema method name has changed to forceScheme and the code above should look like this:

if (!empty($proxy_schema)) {
    URL::forceScheme($proxy_schema);
}

Ok, so I got it. Hopefully this will help someone in the future.

It seems like Laravel ignores the url property in the config\app.php file for http requests (it does state it's only for artisan), and it instead uses either HTTP_HOST or SERVER_NAME provided by apache to generate the domain for URLs.

To override this default url, go to your routes.php file and use the following method:

URL::forceRootUrl('http://subdomain.newurl.com');

This will then force the URL generator to use the new url instead of the HTTP_HOST or SERVER_NAME value.

Alex

Seems the Laravel have more convinient solution.. Check answer there: How do I configure SSL with Laravel 5 behind a load balancer (ssl_termination)?

Following up @TimeLord's solution:

In latest version of laravel the name for forced schema has changed and now it is: URL::forceScheme()

I know this topic is old a.f but I've been solving this issue by replacing the following line in my DatabaseSessionHandler.pdf [@Illuminate/Session]:

    protected function ipAddress()
    {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
//        return $this->container->make('request')->ip();
    }

Of course you need to migrate the sesssion table first and set up the config
(.env Variable SESSION_DRIVER=database)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!