nginx 如何记录Laravel 10阻止的请求?

siv3szwd  于 2023-03-17  发布在  Nginx
关注(0)|答案(1)|浏览(154)

我有一些请求被Laravel 10阻止和其他人没有阻止,我不明白为什么,这就是为什么我想知道如何使Laravel日志所有的请求阻止。
例如,我有一个Nginx记录的请求:

10.0.x.xx - - [16/Mar/2023:11:42:50 +0100] "OPTIONS /my/api/path/foo HTTP/1.1" 204 0 "https://myapi.mywebsite.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"
10.0.x.xx - - [16/Mar/2023:11:42:50 +0100] "POST /my/api/path/foo HTTP/1.1" 500 5697 "https://myapi.mywebsite.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"

在浏览器控制台中,我可以看到以下CORS错误:

Access to XMLHttpRequest at 'https://myapi.mywebsite.com/my/api/path/foo' from origin 'https://myfront.mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

但是,我的config/cors.php应该允许这样的请求:

<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,
];

记录被Laravel阻止的请求将帮助我知道是否真的是Laravel阻止的。

kse8i1jr

kse8i1jr1#

在Laravel 10中,您可以使用Illuminate\Routing\Router类的 blockedRequest 方法来记录被阻塞的请求。

打开应用程序/提供程序/RouteServiceProvider. php文件。

在 Boot 方法中,向Router示例的blockedRequest方法添加回调函数。

use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Log;

public function boot(Router $router)
{
    $router->blockedRequest(function ($request, $throttle) {
        Log::warning('Request blocked', [
            'ip' => $request->ip(),
            'route' => $request->route()->getName()
        ]);
    });
}

这将在请求被阻止时记录一条警告消息。该消息将包括请求的IP地址、用于阻止请求的访问路由的名称。
现在,当请求被阻止时,一条警告消息将记录到Laravel日志文件中。

相关问题