跳到主要内容

宝塔 ECS 配置负载均衡 SLB 的问题

· 阅读需 3 分钟
大刘
一个 web 开发者

在配置 SLB 健康检查非常重要,如果出现以下情况

下述原因可能会导致健康检查异常:
iptables 防火墙配置开启
后端 HTTP 探测码 401、403 与配置不匹配

1、关闭 iptables 服务, CentOS 7 默认用的是 firewalld,也是基于 iptables 的,但 iptables 服务是没安装的

# 开启防火墙,并启用这个服务
sudo systemctl enable firewalld.service
sudo systemctl start firewalld.service
# 停止防火墙,并禁用这个服务
sudo systemctl stop firewalld.service
sudo systemctl disable firewalld.service

如果想在 CentOS 7 改用 iptables 的话,需要安装 iptables 服务

# 安装
sudo yum install iptables-services
# 开启 iptables
sudo systemctl enable iptables
sudo systemctl enable ip6tables
# 启动服务
sudo systemctl start iptables
sudo systemctl start ip6tables

2、如果是宝塔面板的 ECS 服务器,一般监听 80 端口时,最容易发生异常,原因还是服务器 nginx 配置问题,准确的说安装 phpmyadmin 的问题。当启动和停止 phpmyadmin 时,查看 nginx 配置文件 root 配置项会指向 root /www/server/phpmyadmin;root /www/server/stop; 端口也会跟随 phpmyadmin 配置一起变化。好了,问题找到了,那么怎么解决?

更新:最快方式就是在宝塔里设置默认站点即可,下面的不用看了

最快捷方式,手动修改 nginx 配置文件监听端口 80,root 指向 /www/wwwroot/default/,这种方式不能再使用 phpmyadmin

新建配置文件方式,在 /www/server/panel/vhost 目录新建 nginx_slb.conf 文件,添加配置

server
{
listen 80;
server_name slb;
index index.php index.html index.htm default.php default.htm default.html;
root /www/wwwroot/default;
# error_page 404 /404.html;
include enable-php.conf;
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*.(js|css)?$
{
expires 12h;
}
location ~ /.
{
deny all;
}
location / {
if (!-e $request_filename) {
rewrite ^/(.*)/public/ /$1/public/index.php?$query_string last; # 推荐
break;
}
}
access_log /www/wwwlogs/slb.log;
error_log /www/wwwlogs/slb.error.log;
}

完成后,需要在 nginx 配置文件中 phpmyadmin 的 server 前面引入即可

server_tokens off;
access_log off;
include /www/server/panel/vhost/nginx_slb.conf;
server {
listen 888;
server_name phpmyadmin;

3、HTTPS 重定向的次数过多,这是端服务器端口配置问题,修改端口为 80,使 SLB 与 ECS 服务器之间通过 HTTP 转发。如果页面样式错乱, 则将 HTTP 调用改为 HTTPS ,在页面添加

<meta
http-equiv="Content-Security-Policy"
content="upgrade-insecure-requests"
/>

参考: https://blog.csdn.net/zhangyongbink/article/details/86636014

如果是 Laravel 应用,则在 AppServiceProviderboot() 方法中添加以下代码(注意:需要在 SLB 高级配置里勾选“ 通过X-Forwarded-Proto头字段获取SLB的监听协议 ”)

$this->app['request']->server->set('HTTPS', isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 'https' == $_SERVER['HTTP_X_FORWARDED_PROTO']);