dqwh1203 2017-11-07 20:53
浏览 90
已采纳

Laravel 5.4相对而不是绝对302重定向

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?

  • 写回答

1条回答 默认 最新

  • douyuan1752 2017-11-09 08:59
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?