Nginx负载均衡是一个很神奇的技术,很多人都不能很好的掌握这个技术,今天在这里我们向大家详细的介绍下有关Nginx负载均衡的问题。今天小试了一下Nginx负载均衡,真是爽啊!Nginx是什么?

Nginx (”engine x”) 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,它已经在该站点运行超过两年半了。Igor 将源代码以类BSD许可证的形式发布。尽管还是测试版,但是,Nginx 已经因为它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名了。

首先是配置十分的简单,而且功能非常强大。真是相见恨晚。先来看看配置文件怎么写吧

 

 
  
  1. worker_processes 1;  
  2. events {  
  3. worker_connections 1024;  
  4. }  
  5. http{  
  6. upstream myproject {  
  7. #这里指定多个源服务器,ip:端口,80端口的话可写可不写  
  8. server 192.168.43.158:80;  
  9. server 192.168.41.167;  
  10. }  
  11. server {  
  12. listen 8080;  
  13. location / {  
  14. proxy_pass http://myproject;  
  15. }  
  16. }  

 

Nginx负载均衡有哪些功能呢?

如果后面的服务器其中一台坏了,它能自动识别,更牛的是它好了之后Nginx可以马上识别服务器A和B,如果A的响应时间为3,B的响应时间为1,那么Nginx会自动调整访问B的概率是A的3倍,真正做到Nginx负载均衡好的,安装完成了。我在make的时候报了个错,说HTTP Rewrite 模块 有问题,我就

./configure –without-http_rewrite_module
然后再make,make install就可以了。

安装好了之后新建一个配置文件,把上面的配置文件内容拷进去,当然要修改你的IP,保存为比如 load_balance.conf然后启动:

/usr/local/Nginx/sbin/Nginx -c load_balence.conf

由于Nginx的作者是俄国人,所以英文的文档也不是那么完善,对于我来说Nginx的最大优点还是配置简单,功能强大。我曾经配过 apache-jk,那真的不是一般人能配的。太复杂了,而且只能用来做tomcat的Nginx负载均衡

 

 

我们就先看看Nginx的默认虚拟主机在用户通过IP访问,或者通过未设置的域名访问(比如有人把他自己的域名指向了你的ip)的时候生效最关键的一点是,在server的设置里面添加这一行:

 
  
  1. listen 80 default; 

后面的default参数表示这个是默认虚拟主机。

Nginx 禁止IP访问这个设置非常有用。

比如别人通过ip或者未知域名访问你的网站的时候,你希望禁止显示任何有效内容,可以给他返回500.目前国内很多机房都要求网站主关闭空主机头,防止未备案的域名指向过来造成麻烦。就可以这样设置:

 
  
  1. server {  
  2. listen 80 default;  
  3. return 500;  

也可以把这些流量收集起来,导入到自己的网站,只要做以下跳转设置就可以:

 
  
  1. server {  
  2. listen 80 default;  
  3. rewrite ^(.*) http://www.mydomain.com permanent;  

按照如上设置后,确实不能通过IP访问服务器了,但是在应该用中出现当server_name后跟多个域名时,其中一个域名怎么都无法访问:

设置如下:

 
  
  1. server  
  2. {  
  3. listen 80;  
  4. server_name www.abc.com abc.com 

没更改之前,通过server_name 中的www.abc.com abc.com均可访问服务器,加入Nginx 禁止IP访问的设置后,通过abc.com无法访问服务器了,www.abc.com可以访问

用 Nginx -t 检测配置文件会提示warning:

 
  
  1. [warn]: conflicting server name “abc.com” on 0.0.0.0:80, 
    ignored  
  2. the configuration file /usr/local/webserver/Nginx/conf/
    Nginx.conf syntax is ok  
  3. configuration file /usr/local/webserver/Nginx/conf/Nginx.
    conf test is successful 

最后通过在listen 80 default;后再加server_name _;解决,形式如下:

 
  
  1. #禁止IP访问  
  2. server  
  3. {  
  4. listen 80 default;  
  5. server_name _;  
  6. return 500;  

下面我们就向大家详细的介绍有关Nginx配置的相关信息。

 
  
  1. #运行用户   
  2. user nobody nobody;   
  3. #启动进程   
  4. worker_processes 2;   
  5. #全局错误日志及PID文档   
  6. error_log logs/error.log notice;   
  7. pid logs/Nginx.pid;   
  8. #工作模式及连接数上限   
  9. events {   
  10. use epoll;   
  11. worker_connections 1024;   
  12. }   
  13. #设定http服务器,利用他的反向代理功能提供负载均衡支持   
  14. http {   
  15. #设定mime类型   
  16. include conf/mime.types;   
  17. default_type application/octet-stream;   
  18. #设定日志格式   
  19. log_format main '$remote_addr - $remote_user [$time_local] '   
  20. '"$request" $status $bytes_sent '   
  21. '"$http_referer" "$http_user_agent" '   
  22. '"$gzip_ratio"';   
  23. log_format download '$remote_addr - $remote_user [$time_local] '   
  24. '"$request" $status $bytes_sent '   
  25. '"$http_referer" "$http_user_agent" '   
  26. '"$http_range" "$sent_http_content_range"';   
  27. #设定请求缓冲   
  28. client_header_buffer_size 1k;   
  29. large_client_header_buffers 4 4k;   
  30. #开启gzip模块   
  31. gzip on;   
  32. gzip_min_length 1100;   
  33. gzip_buffers 4 8k;   
  34. gzip_types text/plain;   
  35. output_buffers 1 32k;   
  36. postpone_output 1460;   
  37. #设定access log   
  38. access_log logs/access.log main;   
  39. client_header_timeout 3m;   
  40. client_body_timeout 3m;   
  41. send_timeout 3m;   
  42. sendfile on;   
  43. tcp_nopush on;   
  44. tcp_nodelay on;   
  45. keepalive_timeout 65;   
  46. #设定负载均衡的服务器列表   
  47. upstream mysvr {   
  48. #weigth参数表示权值,权值越高被分配到的几率越大   
  49. #本机上的Squid开启3128端口   
  50. server 192.168.8.1:3128 weight=5;   
  51. server 192.168.8.2:80 weight=1;   
  52. server 192.168.8.3:80 weight=6;   
  53. }   
  54. #设定虚拟主机   
  55. server {   
  56. listen 80;   
  57. server_name 192.168.8.1   
  58. www.yejr.com   
  59. ;   
  60. charset gb2312;   
  61. #设定本虚拟主机的访问日志   
  62. access_log logs/www.yejr.com.access.log main;   
  63. #假如访问 /img/*, /js/*, /css/* 资源,则直接取本地文档,不通过squid   
  64. #假如这些文档较多,不推荐这种方式,因为通过squid的缓存效果更好   
  65. location ~ ^/(img|js|css)/ {   
  66. root /data3/Html;   
  67. expires 24h;   
  68. }   
  69. #对 "/" 启用负载均衡   
  70. location / {   
  71. proxy_pass http://mysvr;   
  72. proxy_redirect off;   
  73. proxy_set_header Host $host;   
  74. proxy_set_header X-Real-IP $remote_addr;   
  75. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;   
  76. client_max_body_size 10m;   
  77. client_body_buffer_size 128k;   
  78. proxy_connect_timeout 90;   
  79. proxy_send_timeout 90;   
  80. proxy_read_timeout 90;   
  81. proxy_buffer_size 4k;   
  82. proxy_buffers 4 32k;   
  83. proxy_busy_buffers_size 64k;   
  84. proxy_temp_file_write_size 64k;   
  85. }   
  86. #设定查看Nginx状态的地址   
  87. location /NginxStatus {   
  88. stub_status on;   
  89. access_log on;   
  90. auth_basic "NginxStatus";   
  91. auth_basic_user_file conf/htpasswd;   
  92. }   
  93. }   
  94. }  

备注:conf/htpasswd 文档的内容用 apache 提供的 htpasswd 工具来产生即可,内容大致如下:

3.) 查看 Nginx 运行状态 输入地址http://192.168.8.1/NginxStatus/ 。输入验证帐号密码,即可看到类似如下内容:

 
  
  1. Active connections: 328   
  2. server accepts handled requests   
  3. 9309 8982 28890   
  4. Reading: 1 Writing: 3 Waiting: 324  

第一行表示现在活跃的连接数,第三行的第三个数字表示Nginx运行到

 

nginx配置文件正确与否的检测方法。希望大家在以后的使用中有所收获。

检测nginx配置文件是否正确

 
  
  1. /usr/local/nginx/sbin/nginx -t -c nginx.conf  
  2. -c 配置文件路径  
  3. -g Set global directives. (version >=0.7.4)  
  4. -t 检测文件是否正确不执行  
  5. -v Print version.  
  6. -V Print nginx version, compiler version and configure 
    parameters. 

 

编译时如果使用了–with-debug编译,还可以使用error_log file [ debug_core| debug_http | debug_event …] 来获得debug信息

通过信号对 Nginx配置文件 进行控制

Nginx配置文件 支持下表中的信号:

信号名 作用描述

 

  1. TERM, INT 快速关闭程序,中止当前正在处理的请求   
  2. QUIT 处理完当前请求后,关闭程序   
  3. HUP 重新加载配置,并开启新的工作进程,关闭就的进程,此操作不会中断请求   
  4. USR1 重新打开日志文件,用于切换日志,例如每天生成一个新的日志文件   
  5. USR2 平滑升级可执行程序   
  6. WINCH 从容关闭工作进程  

有两种方式来通过这些信号去控制 Nginx配置文件,第一是通过 logs 目录下的 nginx.pid 查看当前运行的 Nginx 的进程 ID,通过 kill – XXX <pid> 来控制 Nginx,其中 XXX 就是上表中列出的信号名。如果您的系统中只有一个 Nginx 进程,那您也可以通过 killall 命令来完成,例如运行 killall – s HUP nginx 来让 Nginx 重新加载配置。

配置:

 

 
  
  1. use [ kqueue | rtsig | epoll | /dev/poll | select | poll ];
    FreeBSD使用kqueue,Linux选epoll.  
  2. worker_connections number 每个worker的最大连接数  
  3. Maxclient = work_processes * worker_connections 

 

nginx的upstream目前支持4种方式的分配

1、轮询(默认)

每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

2、weight

指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。

2、ip_hash

每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。

3、fair(第三方)

按后端服务器的响应时间来分配请求,响应时间短的优先分配。

4、url_hash(第三方)

按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。

代理只需要在nginx配置文件中增加虚拟主机,然后加入

 
  
  1. \proxy_pass http://localhost:8000; 

 

负载均衡:只需要在http中增加

 
  
  1. upstream tgcluster {#定义负载均衡设备的Ip及设备状态  
  2. ip_hash;  
  3. server 127.0.0.1:9090 down;  
  4. server 127.0.0.1:8080 weight=2;  
  5. server 127.0.0.1:6060;  
  6. server 127.0.0.1:7070 backup;  

在需要使用负载均衡的server中增加

 
  
  1. proxy_pass http://tgcluster/; 

每个设备的状态设置为:

1.down 表示单前的server暂时不参与负载
2.weight 默认为1.weight越大,负载的权重就越大。
3.max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误
4.fail_timeout:max_fails次失败后,暂停的时间。
5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

nginx配置文件支持同时设置多组的负载均衡,用来给不用的server来使用。

client_body_in_file_only 设置为On 可以讲client post过来的数据记录到文件中用来做debug
client_body_temp_path 设置记录文件的目录 可以设置最多3层目录

location 对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡

FASTCGI配置:

请将以下内容保存为fastcgi_params文件,保存于/usr/local/nginx/conf下(Ubuntu可保存于/etc/nginx下),他为我们的FastCGI模块设置了基本的环境变量:

 
  
  1. #fastcgi_params  
  2. fastcgi_param GATEWAY_INTERFACE CGI/1.1;  
  3. fastcgi_param SERVER_SOFTWARE nginx;  
  4. fastcgi_param QUERY_STRING $query_string;  
  5. fastcgi_param REQUEST_METHOD $request_method;  
  6. fastcgi_param CONTENT_TYPE $content_type;  
  7. fastcgi_param CONTENT_LENGTH $content_length;  
  8. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;  
  9. fastcgi_param SCRIPT_NAME $fastcgi_script_name;  
  10. fastcgi_param REQUEST_URI $request_uri;  
  11. fastcgi_param DOCUMENT_URI $document_uri;  
  12. fastcgi_param DOCUMENT_ROOT $document_root;  
  13. fastcgi_param SERVER_PROTOCOL $server_protocol;  
  14. fastcgi_param REMOTE_ADDR $remote_addr;  
  15. fastcgi_param REMOTE_PORT $remote_port;  
  16. fastcgi_param SERVER_ADDR $server_addr;  
  17. fastcgi_param SERVER_PORT $server_port;  
  18. fastcgi_param SERVER_NAME $server_name;  
  19. # PHP only, required if PHP was built with 
    –enable-force-cgi-redirect 

fastcgi_param REDIRECT_STATUS 200;请特别注意加粗的一行,PHP-CGI特别需要此行信息来确定PHP文件的位置。

另外需要在PHP-CGI的配置文件(Ubuntu 上此配置文件位于/etc/php5/cgi/php.ini)中,打开cgi.fix_pathinfo选项:

cgi.fix_pathinfo=1;这样php-cgi方能正常使用SCRIPT_FILENAME这个变量。

接下来在nginx的配置中针对php文件配置其利用FastCGI进程来执行:

 

 
  
  1. server {  
  2. index index.php;  
  3. root /usr/local/nginx/html;  
  4. location ~ .*.php$ {  
  5. include /usr/local/nginx/conf/fastcgi_params; 
    #请根据自己保存的路径进行设置  
  6. fastcgi_index index.php;  
  7. fastcgi_pass 127.0.0.1:9000; 
    #请根据自己的FastCGI绑定的地址和端口进行配置  
  8. }  

 

通知Nginx重新载入配置:

kill -HUP `cat /usr/local/nginx/logs/nginx.pid`Ubuntu用户可以使用init脚本:sudo /etc/init.d/nginx reload

然后启动php-cgi -b 127.0.0.1:9000

如果出现No input file specified表示SCRIPT_FILENAME设置的有问题。使用lighttpd的 spawn-fcgi

 

 
  
  1. get http://www.lighttpd.net/download/lighttpd-1.4.18.tar.bz2 
    #获取Lighttpd的源码包  
  2. tar -xvjf lighttpd-1.4.18.tar.bz2  
  3. cd lighttpd-1.4.18  
  4. ./configure #编译  
  5. make  
  6. cp src/spawn-fcgi /usr/local/bin/spawn-fcgi 
    #取出spawn-fcgi的程序 

以上就是对nginx配置文件如何检测的相关介绍希望大家有所收获。

 

1. 下载最新版的AWStats,基本就是Perl包,所以没必要用apt-get,解压缩到/usr/local/awstats下

wget http://prdownloads.sourceforge.net/awstats/awstats-6.95.tar.gz
tar -xzf awstats-6.95.tar.gz
mv awstats-6.95 /usr/local/awstats

2. 创建一个存放awstats分析数据的目录

mkdir /var/lib/awstats
chown www-data /var/lib/awstats //这是为了让awstats页面上能直接刷新最新数据

3. 自动配置awstats

cd /usr/local/awstats/tools
perl awstats_configure.pl

除了第一步因为是Ngin服务器的关系,所以要选none,其他基本按照提示选默认值

4. 手工编辑Nginx配置文件

1) 修改LogFile路径

LogFile = “/var/log/Nginx/access.log”

如果是压缩格式的日志,可以用LogFile = “zcat /var/log/Nginx/%YYYY-24%MM-24%DD-24.gz|"。这里用zcat是因为其使用管道输出,对系统资源消耗比较小,千万不要忘了最后的管道操作符!

假设原来/etc/Nginx/Nginx.conf中关于log部分是如此定义的:(要小心各个变量之间必须添加的空格,不能少,否则awstats就不认了)

log_format main ‘$remote_addr $remote_user [$time_local] “$request” $status ‘
‘$host $body_bytes_sent $gzip_ratio “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for”‘;

很容易知道,对应awstats配置文件中,LogFormat应该设置为
LogFormat= “%host %logname %time1 %methodurl %code %host_r %bytesd %gzipratio %refererquot %uaquot %otherquot”

最后一个选%otherquot是应为$http_x_forwarded_for在AWstats 6.95中还不认识

3) 将AllowToUpdateStatsFromBrowser=1,便于浏览器中即时刷新数据

5. 更新Awstats的分析记录,测试一下刚才的配置

/usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=yousite.com

如果一切正常,应该看到类似以下的结果:

Create/Update database for config “/etc/awstats/awstats.yoursite.com.conf” by AWStats version 6.95 (build 1.943)
From data in log file “/var/log/Nginx/access.log”…
Phase 1 : First bypass old records, searching new record…
Searching new records from beginning of log file…
Phase 2 : Now process new records (Flush history on disk after 20000 hosts)…
Jumped lines in file: 0
Parsed lines in file: 1234
Found 0 dropped records,
Found 0 corrupted records,
Found 0 old records,
Found 1234 new qualified records.

6. 修改logrotate.d下的Nginx配置文件,在每天切割日志前,更新awstats状态

 
  
  1. /var/log/  nginx  /*.log {  
  2. daily  
  3. missingok  
  4. rotate 7  
  5. compress  
  6. delaycompress  
  7. notifempty  
  8. create 640 www-data www-data  
  9. dateext  
  10. sharedscripts  
  11. prerotate  
  12. /usr/local/awstats/wwwroot/cgi-bin/awstats.pl -update -config=yoursite.com  
  13. sleep 59  
  14. endscript  
  15. postrotate  
  16. if [ -f /var/run/nginx.pid ]; then  
  17. kill -USR1 `cat /var/run/nginx.pid`  
  18. fi  
  19. endscript  

7. 接下来是最关键的NGINX配置文件

 

 
  
  1. #AWStatus Perl CGI server  
  2. server {  
  3. listen 80;  
  4. server_name awstats.yoursite.com;  
  5. access_log /var/log/nginx/awstats.log main;  
  6. error_log /var/log/nginx/awstats_error.log; #这可以为fail2ban留下记录  
  7. root /usr/local/awstats/wwwroot;  
  8. auth_basic “Restricted”;  
  9. auth_basic_user_file /etc/nginx/awstatus.pass;  
  10. location = / {  
  11. rewrite ^ /awstats.pl?config=freshventure.info;  
  12. }  
  13. location ~ .*(\.cgi|\.pl?)$ {  
  14. gzip off; #gzip makes scripts feel slower since they have to complete before getting gzipped  
  15. root /usr/local/awstats/wwwroot/cgi-bin;  
  16. fastcgi_pass 127.0.0.1:8000;  
  17. fastcgi_index awstats.pl;  
  18. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;  
  19. include fastcgi_params;  
  20. }  

 

好了,测试一下http://awstats.yoursite.com,和前文一样,输入密码后,这次看到的应该就awstats的界面了

8. 如果需要配置静态页面,则可以在logrotate中替换掉上面的awstats.pl, 换成

/usr/local/awstats/tools/awstats_buildstaticpages.pl -update -config=yoursite.com -lang=cn -dir=/usr/local/awstats/wwwroot -awstatsprog=/usr/local/awstats/wwwroot/cgi-bin/awstats.pl。

如果需要更频繁的更新访问情况,则可以把这句命令加入到crontab中,例如crontab -e -uwww-data。

然后nginx配置文件相应调整为显示静态网页就可以了。