需求描述

laravel+react前后端分离不同源项目,api接口被throttle斌率限制中间件拦截:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
     ……
    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        ……
        'api' => [
            'throttle:60,1',
            'bindings',
            \Barryvdh\Cors\HandleCors::class,
        ],
       ……
    ];
    ……
}

通过nginx反向代理解决跨域问题后,laravel获取的用户ip,永远是服务器ip,导致大量访问时,api被频控。

解决方法

1.设置nginx反向代理请求头:

location ^~ /api/ {
        rewrite ^/api/(.*)$ /api/$1 break;
        include            uwsgi_params;
        proxy_method       POST;
        proxy_pass         127.0.0.1:8081;
        proxy_set_header   Host $host;
        proxy_set_header   X-real-ip $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    }

2.配置laravelApp\Http\Middleware\TrustProxies.php中间件,设置$proxies:

 protected $proxies = ['1.1.1.1'];//这里填受信代理服务器的ip
Last modification:January 8th, 2021 at 04:21 pm