Nginx 反向代理负载均衡

分类:CentOS教程 阅读:32713 次

nginx.conf配置文件:
user nobody nobody;
worker_processes 4;
error_log logs/error.log crit;
pid logs/nginx.pid;
worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 65535;
}
http {
server_tokens off;
include mime.types;
default_type application/octet-stream;
server_names_hash_bucket_size 128;

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;

upstream mysrv {
server 192.168.1.1:80 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.1.2:80 weight=1 max_fails=2 fail_timeout=30s;
}
upstream bench {
server 192.168.1.3:80 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.1.4:80 weight=1 max_fails=2 fail_timeout=30s;
}
upstream bbs {
server 192.168.1.5:80 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.1.6:80 weight=1 max_fails=2 fail_timeout=30s;
}

include vhost/*.conf;
}

aaa_example_com.conf配置文件:
server {
listen 80;
server_name aaa.example.com;
index index.php index.html index.htm index.shtml;

log_format proxy '$remote_addr| $upstream_addr| $connection| $upstream_status| $time_local| $request|'
' $status| $body_bytes_sent| $bytes_sent| $http_referer|'
' $http_user_agent| $upstream_response_time| $msec| $request_time';
access_log logs/aaa_access.log proxy;

location / {
proxy_passhttp://mysrv;
include proxy.conf;
}

location /bench/ {
proxy_passhttp://bench;
include proxy.conf;
}
}

bbs_example_com.conf配置文件:
server {
listen 80;
server_name bbs.example.com *.bbs.example.com;

log_format proxy '$remote_addr| $upstream_addr| $connection| $upstream_status| $time_local| $request|'
' $status| $body_bytes_sent| $bytes_sent| $http_referer|'
' $http_user_agent| $upstream_response_time| $msec| $request_time';
access_log logs/bbs_access.log proxy;

location / {
proxy_passhttp://bbs;
include proxy.conf;
}

}

proxy.conf配置文件:
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 50m; //允许客户端请求的最大单个文件字节数
client_body_buffer_size 256k; //缓冲区代理缓冲客户端请求的最大字节数
proxy_connect_timeout 30; //连接后端服务器超时时间
proxy_send_timeout 30; //后端服务器发送数据超时时间
proxy_read_timeout 60; //后端服务器响应请求超时时间
proxy_buffer_size 4k; //代理请求缓存区大小
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k; //系统繁忙时可申请的proxy_buffers大小
proxy_temp_file_write_size 64k; //proxy缓存临时文件的大小
proxy_next_upstream error timeout invalid_header http_500 http_503 http_404; //故障转移
proxy_max_temp_file_size 128m;

proxy_set_header指令用于在向反向代理的后端web服务器发起请求时添加指定Header头信息,当后端web服务器上有多个基于域名的虚拟主机时,要通过添加Header头信息Host,来指定请求的域名,这样后端web服务器才能识别该反向代理访问请求由哪个虚拟主机来处理。