Linux下为 ThinkPHP 搭建负载均衡
一、架构与前置准备
二、方案一 Nginx 反向代理负载均衡(最常用)
upstream tp_backend {
least_conn; # 或 ip_hash; 或权重 weight=
server 10.0.0.11:80 max_fails=3 fail_timeout=30s;
server 10.0.0.12:80 max_fails=3 fail_timeout=30s;
keepalive 32;
}
server {
listen 80;
server_name api.example.com;
# 静态资源直接命中
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
root /var/www/your_tp/public;
expires 1y;
add_header Cache-Control "public, immutable";
}
# 反向代理到后端 ThinkPHP
location / {
proxy_pass http://tp_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Request-ID $request_id;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}
# 将 PHP 请求转发到后端 PHP-FPM(示例为本地 9000;远程改为 10.0.0.x:9000)
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info if_not_empty;
fastcgi_pass 127.0.0.1:9000; # 远程:10.0.0.11:9000; 10.0.0.12:9000;
fastcgi_index index.php;
}
}
server {
listen 80;
root /var/www/your_tp/public;
index index.php index.html;
# 隐藏 index.php(PATH_INFO 推荐)
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# 或兼容旧项目:try_files $uri $uri/ /index.php/$uri;
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info if_not_empty;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
}
}
三、其他负载均衡器选项
四、ThinkPHP 与部署要点