没有机器人的Laravel会议 [英] No Laravel Sessions for Bots

查看:55
本文介绍了没有机器人的Laravel会议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在处理大型Laravel项目和Redis存储方面遇到问题.我们将会话存储在Redis中.我们已经有28GB的RAM.但是,它仍然可以相对快地运行到极限,因为我们有很多搜索引擎机器人(每天超过25万次)点击.

I'm having problems with a big Laravel project and the Redis storage. We store our sessions in Redis. We already have 28GB of RAM there. However, it still runs relatively fast to the limit, because we have very many hits (more than 250,000 per day) from search engine bots.

是否有任何优雅的方法可以完全禁用bot会话?我已经实现了自己的会话中间件,如下所示:

Is there any elegant way to completely disable sessions for bots? I have already implemented my own session middleware, which looks like this:

<?php

namespace App\Http\Middleware;

use App\Custom\System\Visitor;

class StartSession extends \Illuminate\Session\Middleware\StartSession
{
    protected function getSessionLifetimeInSeconds()
    {
        if(Visitor::isBot()) {
            return 1;
        }

        return ($this->manager->getSessionConfig()['lifetime'] ?? null) * 60;
    }

    protected function sessionIsPersistent(array $config = null)
    {
        if(Visitor::isBot()) {
            return false;
        }

        $config = $config ?: $this->manager->getSessionConfig();

        return ! in_array($config['driver'], [null, 'array']);
    }
}

这是我检测机器人的功能:

This is my function for detecting bots:

public static function isBot()
    {
        $exceptUserAgents = [
            'Googlebot',
            'Bingbot',
            'Yahoo! Slurp',
            'DuckDuckBot',
            'Baiduspider',
            'YandexBot',
            'Sogou',
            'facebot',
            'ia_archiver',
        ];

        if(!request()->header('User-Agent') || !str_contains(request()->header('User-Agent'), $exceptUserAgents)) {
            return false;
        }

        return true;
    }

不幸的是,这似乎不起作用.有人在这里有小费或经验吗?非常感谢你!

Unfortunately, this does not seem to work. Does anyone have a tip or experience here? Thank you very much!

推荐答案

这就是我自己解决此问题的方式.

This is how I solved this for myself.

  1. 包括使用composer的自动程序检测程序包.我用了这个: https://github.com/JayBizzle/Crawler-Detect

composer require jaybizzle/crawler-detect

创建一个新的中间件类


namespace App\Http\Middleware;

class NoSessionForBotsMiddleware
{
    public function handle($request, \Closure $next)
    {
        if ((new \Jaybizzle\CrawlerDetect\CrawlerDetect)->isCrawler()) {
            \Config::set('session.driver', 'array');
        }

        return $next($request);
    }
}

  1. Kernel类中注册中间件 之前的会话:
  1. Register the middleware before session middleware in the Kernel class:


protected $middlewareGroups = [
    'web' => [
        // ..
        NoSessionForBotsMiddleware::class,
        StartSession::class,
        // ..
    ],
    // ..
];

这篇关于没有机器人的Laravel会议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆