nginx 负载均衡-- 常用nginx配置

时间:2023-03-10 00:47:25
nginx 负载均衡-- 常用nginx配置

中文官方网站
http://wiki.nginx.org/Chs
http://www.howtocn.org/

-------------------------------------------------------------------------------------------

控制站点访问
注:按次序来执行的,所以允许和拒绝要注意顺序
location /www{
root /web/html;
index index.html index.htm
autoindex on;
deny 192.168.0.12 #拒绝这个访问
allow 192.168.1.0/24;#允许这段访问
allow 192.168.2.1;
deny all;
}

-----------------------------------------------------

目录身份验证

# htpasswd -cm /etc/nginx/.htpasswd alice
# htpasswd -cm /etc/nginx/.htpasswd bbb
location /www{
root /web/html;
index index.html index.htm
autoindex on;

auth_basic "AwstatAuth";
auth_basic_user_file /etc/nginx/.htpasswd;

deny 192.168.0.12 #拒绝这个访问
allow 192.168.1.0/24;#允许这段访问
allow 192.168.2.1;
deny all;
}

-----------------------------------------------------

Nginx状态检查
location /nginx_status{
stub_status on;
access_log off;
}
http://locahost/nginx_status
就能看到状态了

-------------------------------------------------------------------------------------------

nginx 负载均衡
nginx默认支持两种转发的策略:
1.轮询
2.ip_hash 同一个IP会访问同一台服务器
upstream php_server_pool[这个是名,可以随便来起]{
ip_hash;
server 192.168.1.10:80 weight=4 max_fails=2 fail_timeout=30s
server 192.168.1.11:80 weight=4 max_fails=2 fail_timeout=30s
server 192.168.1.12:80 weight=4 max_fails=2 fail_timeout=30s
}

写在http{}中
upstream php_server_pool[这个是名,可以随便来起]{ # 默认的转询策略
server 192.168.1.10:80 weight=4 max_fails=2 fail_timeout=30s
server 192.168.1.11:80 weight=4 max_fails=2 fail_timeout=30s
server 192.168.1.12:80 weight=4 max_fails=2 fail_timeout=30s
}
参数说明:
weight:权重 默认为1.weight越大,负载的权重就越大。
max_fails 允许失败的次数
fail_timeout 失败后的超时时间

写在server{}中
location /
{
# 如果后端的服务器返回502,504 执行超时等错误,自动将请求转发到upstream负载均衡池中的
proxy_next_upstream http_502 http_504 error timeout invalid_header; # 可写可不写
proxy_pass http://php_server_pool;
proxy_set_header Host www.baidu.com;# 这样访问这个域名就是转到上面定义的哪几个服务中的一台
proxy_set_header X-Forwarded-For $remote_addr;
}