Loading

LoadBalancer-Nginx-01-Nginx

前提条件

CentOS7:2009

环境

Nginx:1.20.1

安装

# 安装epel(Extra Packages for Enterprise Linux)企业Linux扩展包
yum install -y epel-release
# 验证epel成功加入repo中
yum repolist
# 安装nginx
yum install -y nginx

配置

自动启动

# 启用开机启动
systemctl enable nginx
# 确认开机启动已启用
systemctl is-enabled nginx

启动

# 启动
systemctl start nginx
# 查看状态
systemctl status nginx

防火墙

增加http https 例外规则

firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
firewall-cmd --reload

配置文件

修改默认配置文件/etc/nginx/nginx.conf

# 修改文件 注释或者删除http下server部分的代码
# 以便使/etc/nginx/conf.d/default.conf配置生效
server {
...
}

在目录/etc/nginx/conf.d/ 新增配置文件default.conf

upstream <ServerName1>{
        server <HostIP1>:<Port1>;
        server <HostIP2>:<Port1>;
}

upstream <ServerName2>{
        server <HostIP1>:<Port2>;
        server <HostIP2>:<Port2>;
}

server {
    listen       80;
    server_name  yourdomainname.com;
    root /var/www/nancydemo;

    location /Content/ {
        alias /var/www/nancydemo/Content/;
        location ~*  \.(jpg|jpeg|png|gif|ico|css|js|ttf)$ {
            expires 365d;
        }
    }

    location / {
            proxy_pass http://<ServerName1>;
            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 Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_connect_timeout 10s;
            proxy_read_timeout 3600s;
    }

    location ~ ^/apigateway/<ServerName2>/* {
            proxy_pass http://<ServerName2>;
            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_connect_timeout 10s;
            proxy_read_timeout 3600s;
    }
}

重启nginx服务以便生效

systemctl restart nginx
posted @ 2022-12-11 15:43  知科行技  阅读(35)  评论(0编辑  收藏  举报