Nginx基础学习

参考博客:
http://www.2cto.com/os/201212/176520.html
http://os.51cto.com/art/201111/304611.htm
http://www.cnblogs.com/xiaogangqq123/archive/2011/03/02/1969006.html



1.Nginx.conf学习

#定义Nginx运行的用户和用户组
user www www;
#nginx进程数,建议设置为等于CPU总核心数
worker_processes 8;
#全局错误日志及PID文件,全局错误日志定义类型,有debug, info, notice , warn ,error , crit
error_log  /var/log/nginx/error.log  info;

error_log  /var/log/nginx/error.log  debug;

pid        /var/run/nginx.pid; #进程文件
#一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。
worker_rlimit_nofile 65535;
#工作模式与连接数上限
events {

#参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,

可以大大提高nginx的性能,如果跑在FreeBSD上面,就用kqueue模型。

use epoll;

#单个进程最大连接数(最大连接数=连接数*进程数)

worker_connections 65535;

# 并发总数是 worker_processes 和 worker_connections 的乘积
    # 即 max_clients = worker_processes * worker_connections
    # 在设置了反向代理的情况下,max_clients = worker_processes * worker_connections / 4  为什么
    # 为什么上面反向代理要除以4,应该说是一个经验值
    # 根据以上条件,正常情况下的Nginx Server可以应付的最大连接数为:4 * 8000 = 32000
    # worker_connections 值的设置跟物理内存大小有关
    # 因为并发受IO约束,max_clients的值须小于系统可以打开的最大文件数
    # 而系统可以打开的最大文件数和内存大小成正比,一般1GB内存的机器上可以打开的文件数大约是10万左右
    # 我们来看看360M内存的VPS可以打开的文件句柄数是多少:
    # $ cat /proc/sys/fs/file-max
    # 输出 34336
    # 32000 < 34336,即并发连接总数小于系统可以打开的文件句柄总数,这样就在操作系统可以承受的范围之内
    # 所以,worker_connections 的值需根据 worker_processes 进程数目和系统可以打开的最大文件总数进行适当地进行设置
    # 使得并发总数小于操作系统可以打开的最大文件数目
    # 其实质也就是根据主机的物理CPU和内存进行配置
    # 当然,理论上的并发总数可能会和实际有所偏差,因为主机还有其他的工作进程需要消耗系统资源。
    # ulimit -SHn 65535

# multi_accept on;

}
#设定http服务器
http{

include       /etc/nginx/mime.types; #文件扩展名与文件类型映射表,类型由mime.type文件定义

default_type application/octet-stream; #默认文件类型

#charset utf-8; #默认编码

#设定日志格式
    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  logs/access.log  main;

#sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,

#必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime. 注意:如果图片显示不正常把这个改成off。

sendfile        on;

autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。

tcp_nopush on; #防止网络阻塞

tcp_nodelay on; #防止网络阻塞

#连接超时时间,单位是秒

keepalive_timeout  65;

#FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。

fastcgi_connect_timeout 300;

fastcgi_send_timeout 300;

fastcgi_read_timeout 300;

fastcgi_buffer_size 64k;

fastcgi_buffers 4 64k;

fastcgi_busy_buffers_size 128k;

fastcgi_temp_file_write_size 128k;

#gzip模块设置

gzip on; #开启gzip压缩输出

gzip_min_length 1k; #最小压缩文件大小

gzip_buffers 4 16k; #压缩缓冲区

gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)

gzip_comp_level 2; #压缩等级

gzip_types text/plain application/x-javascript text/css application/xml;

#压缩类型,默认就已经包含textml,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。

gzip_vary on;

#limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用

#设定请求缓冲

client_header_buffer_size    1k;

large_client_header_buffers  4 4k;

include /etc/nginx/conf.d/*.conf;

include /etc/nginx/sites-enabled/*;

#upstream的负载均衡的服务器列表

upstream m.test.fang.com {

#weight参数表示权值,权值越高被分配到的几率越大

server 192.168.8.1:3128 weight=5;

#本机上的Squid开启3128端口

server 192.168.8.2:80  weight=1;

server 192.168.8.3:80  weight=6;

}

upstream mysvr {

#weight参数表示权值,权值越高被分配到的几率越大

server 192.168.8.x:80  weight=1;

server 192.168.8.x:80  weight=6;

}

#虚拟主机的配置

server {

listen       80;#侦听80端口

#定义访问域名

server_name  www.xx.com;

#设定本虚拟主机的访问日志

access_log  logs/www.xx.com.access.log  main;

#默认请求

location / {

          root   /root;      #定义服务器的默认网站根目录位置

          index index.php index.html index.htm;   #定义首页索引文件的名称

          fastcgi_pass  www.xx.com;

          fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;

          include /etc/nginx/fastcgi_params;

}

# 定义错误提示页面

error_page   500 502 503 504 /50x.html;

location = /50x.html {

        root   /root;

}

#静态文件,nginx自己处理

location ~ ^/(images|javascript|js|css|flash|media|static)/ {

        root /var/www/virtual/htdocs;

        #过期30天,静态文件不怎么更新,过期可以设大一点,如果频繁更新,则可以设置得小一点。

        expires 30d;

}

#也可以单独设置,如下

#图片缓存时间设置

location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$

{

     expires 10d;

}

#JS和CSS缓存时间设置

location ~ .*.(js|css)?$

{

     expires 1h;

}

#日志格式设定

log_format access '$remote_addr - $remote_user [$time_local] "$request" '

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" $http_x_forwarded_for';

#定义本虚拟主机的访问日志

access_log ar/loginx/ha97access.log access;

#PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.

location ~ \.php$ {

        root /root;

        fastcgi_pass 127.0.0.1:9000;

        fastcgi_index index.php;

        fastcgi_param SCRIPT_FILENAME /home/www/www$fastcgi_script_name;

        include fastcgi_params;

}

#对以aspx为后缀的请求进行负载均衡

location ~ .*\.aspx$ {

          root   /root;      #定义服务器的默认网站根目录位置

          index index.php index.html index.htm;   #定义首页索引文件的名称

          proxy_pass  http://mysvr ;#请求转向mysvr 定义的服务器列表

          #以下是一些反向代理的配置可删除.

          proxy_redirect off;

          #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP

          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 10m;    #允许客户端请求的最大单文件字节数

          client_body_buffer_size 128k;  #缓冲区代理缓冲用户端请求的最大字节数,

          proxy_connect_timeout 90;  #nginx跟后端服务器连接超时时间(代理连接超时)

          proxy_send_timeout 90;        #后端服务器数据回传时间(代理发送超时)

          proxy_read_timeout 90;         #连接成功后,后端服务器响应时间(代理接收超时)

          proxy_buffer_size 4k;             #设置代理服务器(nginx)保存用户头信息的缓冲区大小

          proxy_buffers 4 32k;               #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置

          proxy_busy_buffers_size 64k;    #高负荷下缓冲大小(proxy_buffers*2)

          proxy_temp_file_write_size 64k;  #设定缓存文件夹大小,大于这个值,将从upstream服务器传

}

#设定查看Nginx状态的地址

location /NginxStatus {

        stub_status              on;

        access_log               on;

        auth_basic              "NginxStatus";

        auth_basic_user_file  conf/htpasswd;

}

#禁止访问 .htxxx 文件

location ~ /\.ht {

        deny all;

}

#本地动静分离反向代理配置

#所有JSP页面均交由tomcat或resin处理

location ~ .(jsp|jspx|do)?$ {

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_pass http://127.0.0.1:8080;

}

#所有静态文件由nginx直接读取不经过tomcat或resin

location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$

{

     expires 15d;

}

location ~ .*.(js|css)?$

{

      expires 1h;

}

}#结束server

}#结束http


二手房的nginx配置

####### begin esf.m.soufun.com #######
server
{
     <% ip_array.each do |ip_array| %>
   listen       <%= ip_array %>:80;<% end %>
   server_name  esf.m.soufun.com;
   index index.html index.htm index.php;
   root  /weblucenedb/webdev/commonm.soufun.com/web/esf;
   location ~* ^/esf_bs/ {
   rewrite ^/esf_bs/(.*) /$1;
   rewrite "^/([a-z]*)_?(\d*)_?b?(\d*)/?m?([0-9,]*)h?(\d*)a?([0-9,]*)c?(\d*)p?([0-9,]*)d?(\d*)x?(?P<x>\d*)o?(?P<o>\d*)/$" /index.php?       purpose=%B1%F0%CA%FB&city=$1&district=$2&comarea=$3&price=$4&room=$5&area=$6&tags=$7&buildclass=$8&equipment=$9&orderby=$x&towards=$o&rewrite last;
   }
   location ~* ^/esf_xzl/ {
   rewrite ^/esf_xzl/(.*) /$1;
   rewrite "^/([a-z]*)_?(\d*)_?b?(\d*)/?m?([0-9,]*)a?([0-9,]*)c?(\d*)p?(\d*)/$" /index.php?     purpose=%D0%B4%D7%D6%C2%A5&city=$1&district=$2&comarea=$3&price=$4&area=$5&tags=$6&propertysubtype=$7&rewrite last;
   }
   location ~* ^/esf_sp/ {
   rewrite ^/esf_sp/(.*) /$1;
   rewrite "^/([a-z]*)_?(\d*)_?b?(\d*)/?m?([0-9,]*)a?([0-9,]*)c?(\d*)p?(\d*)/$" /index.php?purpose=%C9%CC%C6%CC&city=$1&district=$2&comarea=$3&price=$4&area=$5&tags=$6&propertysubtype=$7&rewrite last;
   }
   location ~* ^/esf/ {
   rewrite ^/esf/(.*) /$1;
   rewrite ^/([a-z]+).html /index.php?c=esf&a=index&city=$1 last;
   rewrite ^/([a-z]*)_?(\d*)_?b?(\d*)/?m?([0-9,]*)h?(\d*)a?([0-9,]*)c?(\d*)x?(\d*)f?([0-9,]*)o?(?P<o>\d*)d?(?P<d>\d*)/$ /index.php?   purpose=&city=$1&&district=$2&comarea=$3&price=$4&room=$5&area=$6&tags=$7&orderby=$8&age=$9&towards=$o&equipment=$d&rewrite last;
   rewrite ^/([a-z]+)/([A-Z]+)_([0-9]+).html /index.php?c=esf&a=detail&city=$1&housetype=$2&houseid=$3 last;
   rewrite ^/([a-z]+)/([0-9]+)/([A-Z]+)/([0-9]+).html /index.php?c=esf&a=picDetail&city=$1&houseid=$2&housetype=$3&number=$4 last;
   rewrite ^/([a-z]+)_xm([0-9]+)/$ /index.php?c=esf&a=index&city=$1&projcodes=$2&src=xiaoqu&rewrite last;
   rewrite ^/shop/([a-z]+)_([0-9]+)/$ /index.php?c=esf&a=shop&city=$1&id=$2&type=project&rewrite last;
   rewrite ^/shop/([a-z]+)_([0-9]+)/slist_a1_100/$ /index.php?c=esf&a=shopEsfListInfo&city=$1&id=$2&purpose=all&rewrite last;
   rewrite ^/shop/([a-z]+)_([0-9]+)/zlist_a1_100/$ /index.php?c=esf&a=shopZfListInfo&city=$1&id=$2&purpose=all&rewrite last;
   rewrite ^/sqshop/([a-z]+)_([0-9]+)/$ /index.php?c=esf&a=shop&city=$1&id=$2&type=comerce&rewrite last;
   }

   location ~ .*\.(php|php5)?$
   {
     fastcgi_pass  127.0.0.1:9016;
     fastcgi_index index.php;
     include fastcgi_params;
   }

access_log  /weblucenedb/nginx/logs/esf.m.soufun.com.log  combined;
}


nginx rewrite 参数和例子

本位转自:http://blog.c1gstudio.com/archives/434

正则表达式匹配,其中:

  1.   ~ 为区分大小写匹配
  2.   ~* 为不区分大小写匹配
  3.   !~和!~*分别为区分大小写不匹配及不区分大小写不匹配

文件及目录匹配,其中:

  1. -f和!-f用来判断是否存在文件
  2. -d和!-d用来判断是否存在目录
  3. -e和!-e用来判断是否存在文件或目录
  4. -x和!-x用来判断文件是否可执行

flag标记有:

  1. last 相当于Apache里的[L]标记,表示完成rewrite
  2. break 终止匹配, 不再匹配后面的规则
  3. redirect 返回302临时重定向 地址栏会显示跳转后的地址
  4. permanent 返回301永久重定向 地址栏会显示跳转后的地址

一些可用的全局变量有,可以用做条件判断(待补全)

  1. $args
  2. $content_length
  3. $content_type
  4. $document_root
  5. $document_uri
  6. $host
  7. $http_user_agent
  8. $http_cookie
  9. $limit_rate
  10. $request_body_file
  11. $request_method
  12. $remote_addr
  13. $remote_port
  14. $remote_user
  15. $request_filename
  16. $request_uri
  17. $query_string
  18. $scheme
  19. $server_protocol
  20. $server_addr
  21. $server_name
  22. $server_port
  23. $uri

结合QeePHP的例子

  1. if (!-d $request_filename) {
  2. rewrite ^/([a-z-A-Z]+)/([a-z-A-Z]+)/?(.*)$ /index.php?namespace=user&amp;controller=$1&amp;action=$2&amp;$3 last;
  3. rewrite ^/([a-z-A-Z]+)/?$ /index.php?namespace=user&amp;controller=$1 last;
  4. break;
  5. }

多目录转成参数
abc.domian.com/sort/2 => abc.domian.com/index.php?act=sort&name=abc&id=2

  1. if ($host ~* (.*)/.domain/.com) {
  2. set $sub_name $1;   
  3. rewrite ^/sort//(/d+)//?$ /index.php?act=sort&cid=$sub_name&id=$1 last;
  4. }

目录对换
/123456/xxxx -> /xxxx?id=123456

  1. rewrite ^/(/d+)/(.+)/ /$2?id=$1 last;

例如下面设定nginx在用户使用ie的使用重定向到/nginx-ie目录下:

  1. if ($http_user_agent ~ MSIE) {
  2. rewrite ^(.*)$ /nginx-ie/$1 break;
  3. }

目录自动加“/”

  1. if (-d $request_filename){
  2. rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
  3. }

禁止htaccess

  1. location ~//.ht {
  2.          deny all;
  3. }

禁止多个目录

  1. location ~ ^/(cron|templates)/ {
  2. deny all;
  3. break;
  4. }

禁止以/data开头的文件
可以禁止/data/下多级目录下.log.txt等请求;

  1. location ~ ^/data {
  2.          deny all;
  3.      }

禁止单个目录
不能禁止.log.txt能请求

  1. location /searchword/cron/ {
  2.          deny all;
  3.      }

禁止单个文件

  1. location ~ /data/sql/data.sql {
  2.          deny all;
  3.      }

给favicon.ico和robots.txt设置过期时间;
这里为favicon.ico为99天,robots.txt为7天并不记录404错误日志

  1. location ~(favicon.ico) {
  2. log_not_found off;
  3. expires 99d;
  4. break;
  5. }
  6. location ~(robots.txt) {
  7. log_not_found off;
  8. expires 7d;
  9. break;
  10. }

设定某个文件的过期时间;这里为600秒,并不记录访问日志

  1. location ^~ /html/scripts/loadhead_1.js {
  2.                  access_log   off;
  3.                  root /opt/lampp/htdocs/web;
  4.                  expires 600;
  5.                  break;
  6. }

文件反盗链并设置过期时间
这里的return 412 为自定义的http状态码,默认为403,方便找出正确的盗链的请求
“rewrite ^/ http://leech.c1gstudio.com/leech.gif;”显示一张防盗链图片
“access_log off;”不记录访问日志,减轻压力
“expires 3d”所有文件3天的浏览器缓存

  1. location ~* ^.+/.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {
  2. valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194;
  3. if ($invalid_referer) {
  4.     rewrite ^/ http://leech.c1gstudio.com/leech.gif;
  5.     return 412;
  6.     break;
  7. }
  8. access_log   off;
  9. root /opt/lampp/htdocs/web;
  10. expires 3d;
  11. break;
  12. }

只充许固定ip访问网站,并加上密码

  1. root  /opt/htdocs/www;
  2. allow   208.97.167.194;
  3. allow   222.33.1.2;
  4. allow   231.152.49.4;
  5. deny    all;
  6. auth_basic "C1G_ADMIN";
  7. auth_basic_user_file htpasswd;

将多级目录下的文件转成一个文件,增强seo效果
/job-123-456-789.html 指向/job/123/456/789.html

rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+)/.html$ /job/$1/$2/jobshow_$3.html last;

将根目录下某个文件夹指向2级目录
如/shanghaijob/ 指向 /area/shanghai/
如果你将last改成permanent,那么浏览器地址栏显是/location/shanghai/

  1. rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;

上面例子有个问题是访问/shanghai 时将不会匹配

  1. rewrite ^/([0-9a-z]+)job$ /area/$1/ last;
  2. rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;

这样/shanghai 也可以访问了,但页面中的相对链接无法使用,
如./list_1.html真实地址是/area/shanghia/list_1.html会变成/list_1.html,导至无法访问。

那我加上自动跳转也是不行咯
(-d $request_filename)它有个条件是必需为真实目录,而我的rewrite不是的,所以没有效果

  1. if (-d $request_filename){
  2. rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
  3. }

知道原因后就好办了,让我手动跳转吧

  1. rewrite ^/([0-9a-z]+)job$ /$1job/ permanent;
  2. rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;

文件和目录不存在的时候重定向:

  1. if (!-e $request_filename) {
  2. proxy_pass http://127.0.0.1;
  3. }

域名跳转

  1. server
  2.      {
  3.              listen       80;
  4.              server_name  jump.c1gstudio.com;
  5.              index index.html index.htm index.php;
  6.              root  /opt/lampp/htdocs/www;
  7.              rewrite ^/ http://www.c1gstudio.com/;
  8.              access_log  off;
  9.      }

多域名转向

  1.              server_name  www.c1gstudio.com www.c1gstudio.net;
  2.              index index.html index.htm index.php;
  3.              root  /opt/lampp/htdocs;
  4.              if ($host ~ "c1gstudio/.net") {
  5.              rewrite ^(.*) http://www.c1gstudio.com$1 permanent;
  6.             }

三级域名跳转

  1. if ($http_host ~* "^(.*)/.i/.c1gstudio/.com$") {
  2. rewrite ^(.*) http://top.yingjiesheng.com$1;
  3. break;
  4. }

域名镜向

  1. server
  2.      {
  3.              listen       80;
  4.              server_name  mirror.c1gstudio.com;
  5.              index index.html index.htm index.php;
  6.              root  /opt/lampp/htdocs/www;
  7.              rewrite ^/(.*) http://www.c1gstudio.com/$1 last;
  8.              access_log  off;
  9.      }

某个子目录作镜向

  1. location ^~ /zhaopinhui {
  2.   rewrite ^.+ http://zph.c1gstudio.com/ last;
  3.   break;
  4. }

discuz ucenter home (uchome) rewrite

  1. rewrite ^/(space|network)-(.+)/.html$ /$1.php?rewrite=$2 last;
  2. rewrite ^/(space|network)/.html$ /$1.php last;
  3. rewrite ^/([0-9]+)$ /space.php?uid=$1 last;

discuz 7 rewrite

  1. rewrite ^(.*)/archiver/((fid|tid)-[/w/-]+/.html)$ $1/archiver/index.php?$2 last;
  2. rewrite ^(.*)/forum-([0-9]+)-([0-9]+)/.html$ $1/forumdisplay.php?fid=$2&page=$3 last;
  3. rewrite ^(.*)/thread-([0-9]+)-([0-9]+)-([0-9]+)/.html$ $1/viewthread.php?tid=$2&extra=page/%3D$4&page=$3 last;
  4. rewrite ^(.*)/profile-(username|uid)-(.+)/.html$ $1/viewpro.php?$2=$3 last;
  5. rewrite ^(.*)/space-(username|uid)-(.+)/.html$ $1/space.php?$2=$3 last;
  6. rewrite ^(.*)/tag-(.+)/.html$ $1/tag.php?name=$2 last;

给discuz某版块单独配置域名

  1. server_name  bbs.c1gstudio.com news.c1gstudio.com;
  2.      location = / {
  3.         if ($http_host ~ news/.c1gstudio.com$) {
  4.   rewrite ^.+ http://news.c1gstudio.com/forum-831-1.html last;
  5.   break;
  6. }
  7.      }

discuz ucenter 头像 rewrite 优化

  1. location ^~ /ucenter {
  2.      location ~ .*/.php?$
  3.      {
  4.   #fastcgi_pass  unix:/tmp/php-cgi.sock;
  5.   fastcgi_pass  127.0.0.1:9000;
  6.   fastcgi_index index.php;
  7.   include fcgi.conf;     
  8.      }
  9.      location /ucenter/data/avatar {
  10. log_not_found off;
  11. access_log   off;
  12. location ~ /(.*)_big/.jpg$ {
  13.     error_page 404 /ucenter/images/noavatar_big.gif;
  14. }
  15. location ~ /(.*)_middle/.jpg$ {
  16.     error_page 404 /ucenter/images/noavatar_middle.gif;
  17. }
  18. location ~ /(.*)_small/.jpg$ {
  19.     error_page 404 /ucenter/images/noavatar_small.gif;
  20. }
  21. expires 300;
  22. break;
  23.      }
  24.                        }

jspace rewrite

  1. location ~ .*/.php?$
  2.              {
  3.                   #fastcgi_pass  unix:/tmp/php-cgi.sock;
  4.                   fastcgi_pass  127.0.0.1:9000;
  5.                   fastcgi_index index.php;
  6.                   include fcgi.conf;     
  7.              }
  8.              location ~* ^/index.php/
  9.              {
  10.     rewrite ^/index.php/(.*) /index.php?$1 break;
  11.                   fastcgi_pass  127.0.0.1:9000;
  12.                   fastcgi_index index.php;
  13.                   include fcgi.conf;
  14.              }

基本的 (优化过的)配置

我们将修改的唯一文件是nginx.conf,其中包含Nginx不同模块的所有设置。你应该能够在服务器的/etc/nginx目录中找到nginx.conf。首先,我们将谈论一些全局设置,然后按文件中的模块挨个来,谈一下哪些设置能够让你在大量客户端访问时拥有良好的性能,为什么它们会提高性能。本文的结尾有一个完整的配置文件。

高层的配置

nginx.conf文件中,Nginx中有少数的几个高级配置在模块部分之上。

  • user www-data;
  • pid /var/run/nginx.pid;
  • worker_processes auto;
  • worker_rlimit_nofile 100000;

userpid应该按默认设置 – 我们不会更改这些内容,因为更改与否没有什么不同。

worker_processes 定义了nginx对外提供web服务时的worder进程数。最优值取决于许多因素,包括(但不限于)CPU核的数量、存储数据的硬盘数量及负载模式。不能确定的时候,将其设置为可用的CPU内核数将是一个好的开始(设置为“auto”将尝试自动检测它)。

worker_rlimit_nofile 更改worker进程的最大打开文件数限制。如果没设置的话,这个值为操作系统的限制。设置后你的操作系统和Nginx可以处理比“ulimit -a”更多的文件,所以把这个值设高,这样nginx就不会有“too many open files”问题了。

Events模块

events模块中包含nginx中所有处理连接的设置。

  • events {
  • worker_connections 2048;
  • multi_accept on;
  • use epoll;
  • }

worker_connections设置可由一个worker进程同时打开的最大连接数。如果设置了上面提到的worker_rlimit_nofile,我们可以将这个值设得很高。

记住,最大客户数也由系统的可用socket连接数限制(~ 64K),所以设置不切实际的高没什么好处。

multi_accept 告诉nginx收到一个新连接通知后接受尽可能多的连接。

use 设置用于复用客户端线程的轮询方法。如果你使用Linux 2.6+,你应该使用epoll。如果你使用*BSD,你应该使用kqueue。想知道更多有关事件轮询?看下维基百科吧(注意,想了解一切的话可能需要neckbeard和操作系统的课程基础)

(值得注意的是如果你不知道Nginx该使用哪种轮询方法的话,它会选择一个最适合你操作系统的)。

HTTP 模块

HTTP模块控制着nginx http处理的所有核心特性。因为这里只有很少的配置,所以我们只节选配置的一小部分。所有这些设置都应该在http模块中,甚至你不会特别的注意到这段设置。

  • http {
  • server_tokens off;
  • sendfile on;
  • tcp_nopush on;
  • tcp_nodelay on;
  • }

server_tokens 并不会让nginx执行的速度更快,但它可以关闭在错误页面中的nginx版本数字,这样对于安全性是有好处的。

sendfile可以让sendfile()发挥作用。sendfile()可以在磁盘和TCP socket之间互相拷贝数据(或任意两个文件描述符)。Pre-sendfile是传送数据之前在用户空间申请数据缓冲区。之后用read()将数据从文件拷贝到这个缓冲区,write()将缓冲区数据写入网络。sendfile()是立即将数据从磁盘读到OS缓存。因为这种拷贝是在内核完成的,sendfile()要比组合read()和write()以及打开关闭丢弃缓冲更加有效(更多有关于sendfile)

tcp_nopush 告诉nginx在一个数据包里发送所有头文件,而不一个接一个的发送

tcp_nodelay 告诉nginx不要缓存数据,而是一段一段的发送–当需要及时发送数据时,就应该给应用设置这个属性,这样发送一小块数据信息时就不能立即得到返回值。

  • access_log off;
  • error_log /var/log/nginx/error.log crit;

access_log设置nginx是否将存储访问日志。关闭这个选项可以让读取磁盘IO操作更快(aka,YOLO)。

error_log 告诉nginx只能记录严重的错误。

  • keepalive_timeout 10;
  • client_header_timeout 10;
  • client_body_timeout 10;
  • reset_timedout_connection on;
  • send_timeout 10;

keepalive_timeout 给客户端分配keep-alive链接超时时间。服务器将在这个超时时间过后关闭链接。我们将它设置低些可以让ngnix持续工作的时间更长。

client_header_timeoutclient_body_timeout 设置请求头和请求体(各自)的超时时间。我们也可以把这个设置低些。

reset_timeout_connection告诉nginx关闭不响应的客户端连接。这将会释放那个客户端所占有的内存空间。

send_timeout 指定客户端的响应超时时间。这个设置不会用于整个转发器,而是在两次客户端读取操作之间。如果在这段时间内,客户端没有读取任何数据,nginx就会关闭连接。

  • limit_conn_zone $binary_remote_addr zone=addr:5m;
  • limit_conn addr 100;

limit_conn为给定的key设置最大连接数。这里key是addr,我们设置的值是100,也就是说我们允许每一个IP地址最多同时打开有100个连接。

limit_conn_zone设置用于保存各种key(比如当前连接数)的共享内存的参数。5m就是5兆字节,这个值应该被设置的足够大以存储(32K*5)32byte状态或者(16K*5)64byte状态。

  • include /etc/nginx/mime.types;
  • default_type text/html;
  • charset UTF-8;

include只是一个在当前文件中包含另一个文件内容的指令。这里我们使用它来加载稍后会用到的一系列的MIME类型。


http://my.oschina.net/duxuefeng/blog/34880

Nginx 配置文件详解

user nginx ;

#用户

worker_processes 8;

#工作进程,根据硬件调整,大于等于cpu核数

error_log logs/nginx_error.log crit;

#错误日志

pid logs/nginx.pid;

#pid放置的位置

worker_rlimit_nofile 204800;

#指定进程可以打开的最大描述符

这个指令是指当一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文

件数(ulimit -n)与nginx进程数相除,但是nginx分配请求并不是那么均匀,所以最好与ulimit -n 的值保持一致。

现在在linux 2.6内核下开启文件打开数为65535,worker_rlimit_nofile就相应应该填写65535。

这是因为nginx调度时分配请求到进程并不是那么的均衡,所以假如填写10240,总并发量达到3-4万时就有进程可能超过10240了,这时会返回502错误。

events

{

use epoll;

#使用epoll的I/O 模型

补充说明:

与apache相类,nginx针对不同的操作系统,有不同的事件模型

A)标准事件模型

Select、poll属于标准事件模型,如果当前系统不存在更有效的方法,nginx会选择select或poll

B)高效事件模型

Kqueue:使用于FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X.使用双处理器的MacOS X系统使用kqueue可能会造成内核崩溃。

Epoll:使用于Linux内核2.6版本及以后的系统。

/dev/poll:使用于Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。

Eventport:使用于Solaris 10. 为了防止出现内核崩溃的问题, 有必要安装安全补丁

worker_connections 204800;

#工作进程的最大连接数量,根据硬件调整,和前面工作进程配合起来用,尽量大,但是别把cpu跑到100%就行

每个进程允许的最多连接数, 理论上每台nginx服务器的最大连接数为worker_processes*worker_connections

keepalive_timeout 60;

keepalive超时时间。

client_header_buffer_size 4k;

客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。

分页大小可以用命令getconf PAGESIZE 取得。

[root@web001 ~]# getconf PAGESIZE

4096

但也有client_header_buffer_size超过4k的情况,但是client_header_buffer_size该值必须设置为“系统分页大小”的整倍数。

open_file_cache max=65535 inactive=60s;

这个将为打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive是指经过多长时间文件没被请求后删除缓存。

open_file_cache_valid 80s;

这个是指多长时间检查一次缓存的有效信息。

open_file_cache_min_uses 1;

open_file_cache指令中的inactive参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive时间内一次没被使用,它将被移除。

}

#设定http服务器,利用它的反向代理功能提供负载均衡支持

http

{

include mime.types;

#设定mime类型,类型由mime.type文件定义

default_type application/octet-stream;

log_format main '$host $status [$time_local] $remote_addr [$time_local] $request_uri '

'"$http_referer" "$http_user_agent" "$http_x_forwarded_for" '

'$bytes_sent $request_time $sent_http_x_cache_hit';

log_format log404 '$status [$time_local] $remote_addr $host$request_uri $sent_http_location';

$remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;

$remote_user:用来记录客户端用户名称;

$time_local: 用来记录访问时间与时区;

$request: 用来记录请求的url与http协议;

$status: 用来记录请求状态;成功是200,

$body_bytes_s ent :记录发送给客户端文件主体内容大小;

$http_referer:用来记录从那个页面链接访问过来的;

$http_user_agent:记录客户毒啊浏览器的相关信息;

通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过$remote_add拿到的IP地址是反向代理服务器的iP地址。反向代理服务器在转发请求的http头信息中,可以增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址;

access_log /dev/null;

#用了log_format指令设置了日志格式之后,需要用access_log指令指定日志文件的存放路径;

# access_log /usr/local/nginx/logs/access_log main;

server_names_hash_bucket_size 128;

#保存服务器名字的hash表是由指令server_names_hash_max_size 和server_names_hash_bucket_size所控制的。参数hash bucket size总是等于hash表的大小,并且是一路处理器缓存大小的倍数。在减少了在内存中的存取次数后,使在处理器中加速查找hash表键值成为可能。如果hash bucket size等于一路处理器缓存的大小,那么在查找键的时候,最坏的情况下在内存中查找的次数为2。第一次是确定存储单元的地址,第二次是在存储单元中查找键 值。因此,如果Nginx给出需要增大hash max size 或 hash bucket size的提示,那么首要的是增大前一个参数的大小.

client_header_buffer_size 4k;

客户端请求头部的缓冲区大小,这个可以根据你的系统分页大小来设置,一般一个请求的头部大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE取得。

large_client_header_buffers 8 128k;

客户请求头缓冲大小
nginx默认会用client_header_buffer_size这个buffer来读取header值,如果

header过大,它会使用large_client_header_buffers来读取
如果设置过小HTTP头/Cookie过大 会报400 错误nginx 400 bad request
求行如果超过buffer,就会报HTTP 414错误(URI Too Long)
nginx接受最长的HTTP头部大小必须比其中一个buffer大,否则就会报400的

HTTP错误(Bad Request)。

open_file_cache max 102400

使用字段:http, server, location 这个指令指定缓存是否启用,如果启用,将记录文件以下信息: ·打开的文件描述符,大小信息和修改时间. ·存在的目录信息. ·在搜索文件过程中的错误信息 --没有这个文件,无法正确读取,参考open_file_cache_errors指令选项:
·max -指定缓存的最大数目,如果缓存溢出,最长使用过的文件(LRU)将被移除
例: open_file_cache max=1000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on;

open_file_cache_errors
语法:open_file_cache_errors on | off 默认值:open_file_cache_errors off 使用字段:http, server, location 这个指令指定是否在搜索一个文件是记录cache错误.

open_file_cache_min_uses

语法:open_file_cache_min_uses number 默认值:open_file_cache_min_uses 1 使用字段:http, server, location 这个指令指定了在open_file_cache指令无效的参数中一定的时间范围内可以使用的最小文件数,如 果使用更大的值,文件描述符在cache中总是打开状态.
open_file_cache_valid

语法:open_file_cache_valid time 默认值:open_file_cache_valid 60 使用字段:http, server, location 这个指令指定了何时需要检查open_file_cache中缓存项目的有效信息.

client_max_body_size 300m;

设定通过nginx上传文件的大小

sendfile on;

#sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,
对于普通应用,必须设为on。
如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统uptime。

tcp_nopush on;

此选项允许或禁止使用socket的TCP_CORK的选项,此选项仅在使用sendfile的时候使用

proxy_connect_timeout 90; 
#后端服务器连接的超时时间_发起握手等候响应超时时间

proxy_read_timeout 180;

#连接成功后_等候后端服务器响应时间_其实已经进入后端的排队之中等候处理(也可以说是后端服务器处理请求的时间)

proxy_send_timeout 180;

#后端服务器数据回传时间_就是在规定时间之内后端服务器必须传完所有的数据

proxy_buffer_size 256k;

#设置从被代理服务器读取的第一部分应答的缓冲区大小,通常情况下这部分应答中包含一个小的应答头,默认情况下这个值的大小为指令proxy_buffers中指定的一个缓冲区的大小,不过可以将其设置为更小

proxy_buffers 4 256k;

#设置用于读取应答(来自被代理服务器)的缓冲区数目和大小,默认情况也为分页大小,根据操作系统的不同可能是4k或者8k

proxy_busy_buffers_size 256k;

proxy_temp_file_write_size 256k;

#设置在写入proxy_temp_path时数据的大小,预防一个工作进程在传递文件时阻塞太长

proxy_temp_path /data0/proxy_temp_dir;

#proxy_temp_path和proxy_cache_path指定的路径必须在同一分区
proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
#设置内存缓存空间大小为200MB,1天没有被访问的内容自动清除,硬盘缓存空间大小为30GB。

keepalive_timeout 120;

keepalive超时时间。

tcp_nodelay on;

client_body_buffer_size 512k;
如果把它设置为比较大的数值,例如256k,那么,无论使用firefox还是IE浏览器,来提交任意小于256k的图片,都很正常。如果注释该指令,使用默认的client_body_buffer_size设置,也就是操作系统页面大小的两倍,8k或者16k,问题就出现了。
无论使用firefox4.0还是IE8.0,提交一个比较大,200k左右的图片,都返回500 Internal Server Error错误

proxy_intercept_errors on;

表示使nginx阻止HTTP应答代码为400或者更高的应答。

upstream img_relay {

server 127.0.0.1:8027;

server 127.0.0.1:8028;

server 127.0.0.1:8029;

hash $request_uri;

}

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

1、轮询(默认)

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

2、weight
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
例如:
upstream bakend {
server 192.168.0.14 weight=10;
server 192.168.0.15 weight=10;
}

2、ip_hash
每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
例如:
upstream bakend {
ip_hash;
server 192.168.0.14:88;
server 192.168.0.15:80;
}

3、fair(第三方)
按后端服务器的响应时间来分配请求,响应时间短的优先分配。
upstream backend {
server server1;
server server2;
fair;
}

4、url_hash(第三方)

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

例:在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法

upstream backend {
server squid1:3128;
server squid2:3128;
hash $request_uri;
hash_method crc32;
}

tips:

upstream bakend{#定义负载均衡设备的Ip及设备状态
ip_hash;
server 127.0.0.1:9090 down;
server 127.0.0.1:8080 weight=2;
server 127.0.0.1:6060;
server 127.0.0.1:7070 backup;
}
在需要使用负载均衡的server中增加
proxy_pass http://bakend/;

每个设备的状态设置为:
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进行匹配.可以进行重定向或者进行新的代理 负载均衡

server

#配置虚拟机

{

listen 80;

#配置监听端口

server_name image.***.com;

#配置访问域名

location ~* \.(mp3|exe)$ {

#对以“mp3或exe”结尾的地址进行负载均衡

proxy_pass http://img_relay$request_uri;

#设置被代理服务器的端口或套接字,以及URL

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

#以上三行,目的是将代理服务器收到的用户的信息传到真实服务器上

}

location /face {

if ($http_user_agent ~* "xnp") {

rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;

}

proxy_pass http://img_relay$request_uri;

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 502 = @fetch;

}

location @fetch {

access_log /data/logs/face.log log404;

#设定本服务器的访问日志

rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;

}

location /image {

if ($http_user_agent ~* "xnp") {

rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;

}

proxy_pass http://img_relay$request_uri;

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 502 = @fetch;

}

location @fetch {

access_log /data/logs/image.log log404;

rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;

}

}

server

{

listen 80;

server_name *.***.com *.***.cn;

location ~* \.(mp3|exe)$ {

proxy_pass http://img_relay$request_uri;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

location / {

if ($http_user_agent ~* "xnp") {

rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect;

}

proxy_pass http://img_relay$request_uri;

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 http://i1.***img.com/help/noimg.gif;

error_page 404 502 = @fetch;

}

location @fetch {

access_log /data/logs/baijiaqi.log log404;

rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect;

}

#access_log off;

}

server

{

listen 80;

server_name *.***img.com;

location ~* \.(mp3|exe)$ {

proxy_pass http://img_relay$request_uri;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

location / {

if ($http_user_agent ~* "xnp") {

rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif;

}

proxy_pass http://img_relay$request_uri;

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 http://i1.***img.com/help/noimg.gif;

error_page 404 = @fetch;

}

#access_log off;

location @fetch {

access_log /data/logs/baijiaqi.log log404;

rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect;

}

}

server

{

listen 8080;

server_name ngx-ha.***img.com;

location / {

stub_status on;

access_log off;

}

}

server {

listen 80;

server_name imgsrc1.***.net;

root html;

}

server {

listen 80;

server_name ***.com w.***.com;

# access_log /usr/local/nginx/logs/access_log main;

location / {

rewrite ^(.*)$ http://www.***.com/ ;

}

}

server {

listen 80;

server_name *******.com w.*******.com;

# access_log /usr/local/nginx/logs/access_log main;

location / {

rewrite ^(.*)$ http://www.*******.com/;

}

}

server {

listen 80;

server_name ******.com;

# access_log /usr/local/nginx/logs/access_log main;

location / {

rewrite ^(.*)$ http://www.******.com/;

}

}

location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
}

#设定查看Nginx状态的地址

location ~ /\.ht {
deny all;
}

#禁止访问.htxxx文件

}

注释:变量

Ngx_http_core_module模块支持内置变量,他们的名字和apache的内置变量是一致的。

首先是说明客户请求title中的行,例如$http_user_agent,$http_cookie等等。

此外还有其它的一些变量

$args此变量与请求行中的参数相等

$content_length等于请求行的“Content_Length”的值。

$content_type等同与请求头部的”Content_Type”的值

$document_root等同于当前请求的root指令指定的值

$document_uri与$uri一样

$host与请求头部中“Host”行指定的值或是request到达的server的名字(没有Host行)一样

$limit_rate允许限制的连接速率

$request_method等同于request的method,通常是“GET”或“POST”

$remote_addr客户端ip

$remote_port客户端port

$remote_user等同于用户名,由ngx_http_auth_basic_module认证

$request_filename当前请求的文件的路径名,由root或alias和URI request组合而成

$request_body_file

$request_uri含有参数的完整的初始URI

$query_string与$args一样

$sheeme http模式(http,https)尽在要求是评估例如

Rewrite ^(.+)$ $sheme://example.com$; Redirect;

$server_protocol等同于request的协议,使用“HTTP/或“HTTP/

$server_addr request到达的server的ip,一般获得此变量的值的目的是进行系统调用。为了避免系统调用,有必要在listen指令中指明ip,并使用bind参数。

$server_name请求到达的服务器名

$server_port请求到达的服务器的端口号

$uri等同于当前request中的URI,可不同于初始值,例如内部重定向时或使用index

nginx中文维基百科 http://wiki.nginx.org/NginxChs

http://www.queryer.cn/DOC/nginxCHS/index.html

posted on 2015-08-05 12:58  Ryanyanglibin  阅读(552)  评论(0编辑  收藏  举报

导航