PHP Behind a Load Balancer
PHP relies heavily on $_SERVER variables for request information. Behind a load balancer, these variables reflect the proxy connection, not the client — leading to broken HTTPS detection, wrong client IPs, and session issues.
HTTPS Detection
PHP checks $_SERVER['HTTPS'], but the load balancer terminates SSL:
// In your bootstrap or .htaccess
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
$_SERVER['HTTPS'] = 'on';
}Or in Apache .htaccess:
SetEnvIf X-Forwarded-Proto "https" HTTPS=onReal Client IP
function getClientIp(): string {
$headers = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];
foreach ($headers as $header) {
if (!empty($_SERVER[$header])) {
// X-Forwarded-For can contain multiple IPs
$ips = explode(',', $_SERVER[$header]);
return trim($ips[0]);
}
}
return $_SERVER['REMOTE_ADDR'];
}Session Handling
File sessions break with multiple servers. Switch to Redis:
; php.ini
session.save_handler = redis
session.save_path = "tcp://redis-service:6379"Health Check
// healthz.php
http_response_code(200);
echo 'ok';
exit;Keep it simple — don't include your framework bootstrap, which might fail and return a 500 to the load balancer.
Bugsly's PHP SDK hooks into error handlers and exception handlers to capture errors with request context, including the real client IP parsed from proxy headers.
Try Bugsly Free
AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.
Get Started FreeRelated Articles
Vue.js Debugging Tips for Faster Development
Essential Vue.js debugging techniques including DevTools usage, reactivity debugging, composition API inspection, and common pitfall solutions.
Read moreFix Cache Error in Haskell
Learn how to fix the Cache error in Haskell. Step-by-step guide with code examples and solutions. Quick, practical guide for developers.
Read moreFix NotFoundError in Angular
Resolve Angular routing NotFoundError and 404 issues, covering wildcard routes, lazy-loaded modules, and hash location strategy.
Read moreFix Cache Error in Kotlin
Learn how to fix the Cache error in Kotlin. Step-by-step guide with code examples and solutions. Quick, practical guide for developers.
Read more