emotality/laravel-block-cf-origin

Laravel package to block direct requests to your Cloudlfare-protected origin server.

1.0.1 2024-05-07 01:34 UTC

This package is auto-updated.

Last update: 2024-11-07 02:39:48 UTC


README

License Latest Version Total Downloads

Laravel package to block direct requests to your Cloudlfare-protected origin server.

Overview

This packages should only be used when the following applies:

  1. You can't add firewall rules (to only accept requests from CF Edge IP addresses) because your server is shared with other projects that don't use Cloudflare. If you have a single app running on your server, rather add firewall rules.
  2. You can't add deny/allow rules to your Nginx/Apache config because you are using the set_real_ip_from / mod_remoteip module to forward the user's real IP (X-Forwarded-For). If you don't need to forward the user's real IP, rather add deny/allow rules to your Nginx/Apache config.
  3. You can't install cloudflared and create a tunnel. Read more

See Useful Links section below for more information.

Requirements

  • PHP 8.0+
  • PHP Redis extension
  • Laravel 9.0+

*Note: This package only supports the Redis cache driver!

Installation

  1. composer require emotality/laravel-block-cf-origin
  2. php artisan vendor:publish --provider="Emotality\Cloudflare\CloudflareBlockOriginServiceProvider"
  3. Add the middleware in app/Http/Kernel.php:
protected $middleware = [
    \Emotality\Cloudflare\BlockNonCloudflareRequests::class, // Top is preferred
    ...
];
  1. Add the cronjob to update Cloudflare's netmasks:
protected function schedule(Schedule $schedule): void
{
    ...
    $schedule->call(new \Emotality\Cloudflare\GetNetmasks)->weekly();
}
  1. Update your config/cloudflare-block.php config and .env accordingly.
  2. Add FastCGI (PHP-FPM) param to your Nginx config:
server {
    server_name example.com;
    ...

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param CF_EDGE_IP $realip_remote_addr; <<----- HERE
        include fastcgi_params;
    }
}

$realip_remote_addr will be Cloudflare's IP if the request went through a Cloudflare Edge proxy, or the user's IP if the request was direct.
$remote_addr will be the user's IP address.

Useful Links

Contributing

This package is in its early stages, feel free to report any issues or suggest improvements. Please use the master branch for any pull requests.

License

laravel-block-cf-origin is released under the MIT license. See LICENSE for details.