Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
960 views
in Technique[技术] by (71.8m points)

php - Laravel 5.4 relative instead of absolute 302 redirects

I'm having issues with a new Laravel app behind a load balancer. I would like to have Laravel do the Auth middleware 302 redirects to relative path like /login instead of the http://myappdomain.com/login is actually doing.

I only see 301 redirects in the default .htaccess Laravel ships which makes me believe the behavior is right within Laravel, am I wrong?

Can someone point me in the right direction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you need to properly determine whether a request was secure when behind a load balancer you need to let the framework know that you're behind a proxy. This will ensure that the route() and url() helpers generate correct URLs and remove the need to create relative redirects which are both not 100% supported by browsers and also won't work properly when serving a webpage from a sub-path.

This is what we use to solve this problem and it's working so far for us:

.env

LOAD_BALANCER_IP_MASK=aaa.bbb.ccc.ddd/xx #Subnet mask

LoadBalanced Middleware

class LoadBalanced { 
      public function handle($request, $next) {
          if (env("LOAD_BALANCER_IP_MASK")) {
             $request->setTrustedProxies([ env("LOAD_BALANCER_IP_MASK") ]);
          }
          $next($request);
     }
}

Then put the middleware in your Kernel.php:

protected $middleware = [ 
    LoadBalanced::class,
    //.... It shouldn't matter if it's first or last as long as other global middleware don't need it

];

This is a feature available to Laravel because it is using the Symfony request as a base. How this work is that the load balancer forwards some important headers. Symfony currently understands:

 protected static $trustedHeaders = array(
    self::HEADER_FORWARDED => 'FORWARDED',
    self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',
    self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST',
    self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
    self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT',
);

which have information regarding the user making the request to the load balancer and the protocol used.

Also according to framework comments:

The FORWARDED header is the standard as of rfc7239.

The other headers are non-standard, but widely used by popular reverse proxies (like Apache mod_proxy or Amazon EC2).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...