Skip to content

Instantly share code, notes, and snippets.

@zhanglianxin
Created April 20, 2025 13:53
Show Gist options
  • Save zhanglianxin/a621fd28ba7116cca4eb6861fff92aa9 to your computer and use it in GitHub Desktop.
Save zhanglianxin/a621fd28ba7116cca4eb6861fff92aa9 to your computer and use it in GitHub Desktop.
Fix: client IP resolution for Flarum(v1.x) behind proxy
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Flarum\Extend;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class ForwardedIpMiddleware implements MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler): ResponseInterface
{
$server = $request->getServerParams();
$ip = match (true) {
isset($server['HTTP_X_FORWARDED_FOR']) => trim(explode(
',', $server['HTTP_X_FORWARDED_FOR'])[0] ?? ''),
isset($server['HTTP_X_REAL_IP']) => trim($server['HTTP_X_REAL_IP']),
$server['REMOTE_ADDR'] !== 'unix:' => $server['REMOTE_ADDR'],
default => '127.0.0.1',
};
return $handler->handle($request->withAttribute('ipAddress',
$ip ?: '127.0.0.1'
));
}
}
return [
// Register extenders here to customize your forum!
(new Extend\Middleware('api'))
->add(ForwardedIpMiddleware::class),
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment