ini 使用nginx缓存并响应Web请求#nginx #php #performance #laravel

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ini 使用nginx缓存并响应Web请求#nginx #php #performance #laravel相关的知识,希望对你有一定的参考价值。

#php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Filesystem\Filesystem;

class CacheResponse
{
    /**
     * The filesystem instance.
     *
     * @var \Illuminate\Filesystem\Filesystem
     */
    protected $files;

    /**
     * Constructor.
     *
     * @var \Illuminate\Filesystem\Filesystem  $files
     */
    public function __construct(Filesystem $files)
    {
        $this->files = $files;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        if ($this->shouldCache($request, $response)) {
            $this->cacheResponse($request, $response);
        }

        return $response;
    }

    /**
     * Determines whether the given request/response should be cached.
     *
     * @param  \Illuminate\Http\Response  $response
     * @return bool
     */
    protected function shouldCache($request, $response)
    {
        return $request->isMethod('GET') && $response->getStatusCode() == 200;
    }

    /**
     * Cache the response to a file.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Http\Response  $response
     * @return void
     */
    protected function cacheResponse($request, $response)
    {
        list($path, $file) = $this->getDirectoryAndFileNames($request);

        $this->files->makeDirectory($path, 0775, true, true);

        $this->files->put($path.$file, $response->getContent());
    }

    /**
     * Get the names of the directory and file.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function getDirectoryAndFileNames($request)
    {
        $segments = explode('/', ltrim($request->getPathInfo(), '/'));

        $file = array_pop($segments).'.html';

        return [$this->getCachePath(implode('/', $segments)), $file];
    }

    /**
     * Get the path to the cache directory.
     *
     * @param  string  $path
     * @return string
     */
    protected function getCachePath($path = '')
    {
        return public_path('page-cache/'.($path ? trim($path, '/').'/' : $path));
    }
}


#nginx
location / {
    try_files $uri $uri/ /page-cache/$uri.html /index.php?$query_string;
}


# ref:  https://github.com/laravel/laravel.com/pull/73#issue-77554608
@package https://github.com/JosephSilber/page-cache

以上是关于ini 使用nginx缓存并响应Web请求#nginx #php #performance #laravel的主要内容,如果未能解决你的问题,请参考以下文章

Nginx内容缓存

ini nginx中的完整请求/响应正文日志记录

ini nginx中的完整请求/响应正文日志记录

Nginx缓存配置以及nginx ngx_cache_purge模块的使用

Nginx配置反向代理访问内部服务

nginx的web缓存服务环境部署记录