Centos7.4 Nginx反向代理+负载均衡配置

时间:2021-07-21 19:59:00

Ningx是一款高性能的HTTP和反向代理服务器,配置起来也比较简单。

测试环境:

  172.16.65.190  Nginx-反向代理

  172.16.65.191  Ningx-Web

  172.16.65.192  Nginx-Web

在三台Server安装Nginx:

# yum install -y nginx

在172.16.65.190配置Nginx反向代理+负载均衡:

# vim /etc/nginx/nginx.conf

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf; events {
worker_connections 1024;
} http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048; include /etc/nginx/mime.types;
default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory.
include /etc/nginx/conf.d/*.conf;

# 后端Web服务器,默认使用轮询机制
upstream proxy_test {
server 172.16.65.191:80 weight=1;
server 172.16.65.192:80 weight=1;
ip hash;  
} server {
listen 80;  # 监听的端口
server_name www.test.com;  # 监听的域名
location /abc/ {  # 监听域名的二级域名
proxy_pass http://proxy_test/; # 这里的proxy_test和上面的upstream proxy_test对应
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
} error_page 404 /404.html;
location = /40x.html {
} error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
# nginx -s reload    # 重新加载Nginx配置文件

后端Web配置

默认页面路径 /usr/share/nginx/html/index.html

在172.16.65.191 配置默认页面内容为Server001,启动Nginx

在172.16.65.192 配置默认页面内容为Server002,启动Nginx

测试效果

在Client配置Hosts解析www.test.com

第一次访问

Centos7.4 Nginx反向代理+负载均衡配置

第二次访问

Centos7.4 Nginx反向代理+负载均衡配置