Nginx学习总结

Nginx高性能HTTP和反向代理服务器

局限:只支持HTTP和Mail两种

Nginx使用高效的网络I/O模型,针对不同的Linux 发布版
     epoll(Linux 2.6内核)
     kqueue(FreeBSD)
     eventport(Solaris 10)

Nginx服务器能够支持高达50000个并发连接数的响应,MEM,CPU资源消耗较低(实际生产环境2~4万并发连接数)

Nginx优势
     配置文件简单
     支持Rewrite重写
          能够根据域名,URL,将HTTP请求分到不同的后端服务器
     支持检查服务器功能
          后端某个Web服务器down,不会影响访问
     节省带宽
          支持GZIP压缩,可以添加浏览器本地缓存的Header头
     稳定性高
     支持热部署

Nginx安装与配置

centos or redhat
yum install nginx

ubuntu
apt-get install nginx

local repo config
/etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/
gpgcheck=0
enabled=1


Nginx配置文件

详细配置文件相关请参考如下连接:

  user  www www;     #主进程以root用户启动,然后切换为当前选项配置USER和GROUP,默认为nobody,默认只配置用户USER,那么组也使用USER名称
  worker_processes  2;     #一般为内核数量
  pid /var/run/nginx.pid;     #PID文件位置,例如重新加载配置 kill -HUP `cat /var/log/nginx.pid`
 
  # [ debug | info | notice | warn | error | crit ] 
  error_log  /var/log/nginx.error_log  info;     #error log位置 不用域日志登记不同
                                                 #in the main section - error
                                                 #in the HTTP section - crit
                                                 #in the server section - crit
 
  events {     #Nginx如何控制connection
    worker_connections   2000;     #worker可以开启的连接数量
    # use [ kqueue | rtsig | epoll | /dev/poll | select | poll ] ;     
    use kqueue;     #使用哪种IO网络模型,默认情况根据configure操作系统来决定 epoll在linux版本比较常用
  }

### 一般来说  max clients = worker_processes * worker_connections
### 反向代理  max clients = worker_processes * worker_connections/4

 
  http {     #核心HTTP Server配置
    include       conf/mime.types;     #可以引入其他的配置文件
    default_type  application/octet-stream;     #指定MIME-type,一般情况下不用配置
 
    log_format main      '$remote_addr - $remote_user [$time_local]  '     #日志格式 main为日志格式名称,方便其他位置引用,不允许重复
      '"$request" $status $bytes_sent '
      '"$http_referer" "$http_user_agent" '
      '"$gzip_ratio"';

    log_format download  '$remote_addr - $remote_user [$time_local]  '
      '"$request" $status $bytes_sent '
      '"$http_referer" "$http_user_agent" '
      '"$http_range" "$sent_http_content_range"';

       # $remote_addr:反向代理服务器地址
       # $remote_user:远程客户端名称
       # [$time_local]:访问时间与时区
       # $request:记录请求的URL和协议
       # $status:记录请求状态
       # $body_bytes_sent:客户端发送body内松大小
       # $http_referer:从哪个页面链接访问而来
       # $http_user_agent:记录client浏览器相关信息
       # $http_x_forwarded_for:记录原有client IP地址和原client请求server IP地址
 
    client_header_timeout  3m;     #指定多长时间等待客户端发送一个请求头
    client_body_timeout    3m;     #从客户端读取body超时时间
    send_timeout           3m;     #指定为客户端响应超时时间
 
    client_header_buffer_size    1k;     #客户端headerbuffer大小
    large_client_header_buffers  4 4k;     #最大headerbuffer大小
 
    gzip on;     #开启gzip压缩
    gzip_min_length  1100;     #Content-Length大于此长度才会被压缩
    gzip_buffers     4 8k;     # compress buffer
    gzip_types       text/plain;     #添加额外压缩类型,默认已包括text/html
 
    output_buffers   1 32k;
    postpone_output  1460;
 
    sendfile         on;     #sendfile模式,效率更高,直接通过kernel,而不经过用户空间
    tcp_nopush       on;     #有点深奥,没花时间研究,跟sendfile一同使用
 
    tcp_nodelay      on;     #同上
    send_lowat       12000;
 
    keepalive_timeout  75 20;     #指定的超时时间,与客户保持连接。服务器将在此时间后关闭连接。
 
    # lingering_time     30;
    # lingering_timeout  10;
    # reset_timedout_connection  on;
 
 
    server {     #虚拟服务器配置 基于IP和基于域名两种
      listen        one.example.com;     #监听服务器,地址和端口,默认绑定80端口
      server_name   one.example.com  www.one.example.com;     #访问的名称支持正则表达式
 
      access_log   /var/log/nginx.access_log  main;     
     
          # access log位置
          # 必须有写入权限,当前定义用户
          # 写入过程打开,写入,关闭,可以设置缓冲
 
      location / {     #根据URL进行不同配置
          
          # ~区分大小写
          # ~*不区分大小写
          # / 匹配所有
          # =精确匹配,停止搜索其他location
          # ^~匹配时,停止搜索其他location
          ######################location匹配优先级########################
          #= 精确匹配会第一个被处理。如果发现精确匹配,nginx停止搜索其他匹配。
          #普通字符匹配,正则表达式规则和长的块规则将被优先和查询匹配,也就是说如果该项匹配还需去看有没有正则表达式匹配和更长的匹配。
          #^~ 则只匹配该规则,nginx停止搜索其他匹配,否则nginx会继续处理其他location指令。
          #最后匹配理带有"~"和"~*"的指令,如果找到相应的匹配,则nginx停止搜索其他匹配;当没有正则表达式或者没有正则表达式被匹配的情况下,那么匹配程度最高的逐字匹配指令会被使用。


        proxy_pass         http://127.0.0.1/;     #代理服务器地址和URL映射
        proxy_redirect     off;     #在响应头更新Location和Refresh在代理服务器
 
        proxy_set_header   Host             $host;     #许重新定义和添加request header在代理服务器    
        proxy_set_header   X-Real-IP        $remote_addr;
        # proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
 
        client_max_body_size       10m;     #request body最大大小
        client_body_buffer_size    128k;     #request body buffer大小
 
        client_body_temp_path      /var/nginx/client_body_temp;     #缓冲临时写入文件
 
        proxy_connect_timeout      90;     #超时时间连接到后端服务器,一般不能超过75秒
        proxy_send_timeout         90;     #request连到到后端服务器时间,只两次传输,不算开始传到结束
        proxy_read_timeout         90;     #读取代理服务器响应时间
        proxy_send_lowat           12000;     #FreeBSD才有用
 
        proxy_buffer_size          4k;     #读取代理服务器,Response缓冲区
        proxy_buffers              4 32k;     #数量和缓冲大小读取answer和proxy server
        proxy_busy_buffers_size    64k;
        proxy_temp_file_write_size 64k;     #写入临时文件缓存
 
        proxy_temp_path            /var/nginx/proxy_temp;     #request写入位置
 
        charset  koi8-r;     #指定Content-Type的响应编码
      }
 
      error_page  404  /404.html;     #错误页面位置
 
      location /404.html {
        root  /spool/www;     # 文档根路径 /spool/www/404.html
 
        charset         on;
        source_charset  koi8-r;     #允许重新编码 proxy server或是FastCGI-server
      }
 
      location /old_stuff/ {
        rewrite   ^/old_stuff/(.*)$  /new_stuff/$1  permanent;
      }
 
      location /download/ {
        valid_referers  none  blocked  server_names  *.example.com;
 
        if ($invalid_referer) {
          #rewrite   ^/   http://www.example.com/;
          return   403;
        }
 
        # rewrite_log  on;
        # rewrite /download/*/mp3/*.any_ext to /download/*/mp3/*.mp3
        rewrite ^/(download/.*)/mp3/(.*)\..*$ /$1/mp3/$2.mp3 break;
 
        root         /spool/www;
        # autoindex    on;
        access_log   /var/log/nginx-download.access_log  download;
      }
 
          ####################Nginx Rewrite##################
          # 规则相关命令if,rewrite,set,return,break
          # break:完成当前规则,不在处理rewrite命令
          # if:条件判断,只支持单if
          ###条件:
             1 变量名:不包括空字符串或是0开始字符
             2 变量可以使用 = 等于 != 不等于
             3 正则表达式可以使用 ~* 和 ~
             4 ~区分大小写字母的匹配
             5 ~* 不区分大小写字母的匹配
             6 !~和!~*作用同5相反
             7 -f 文件是否存在
             8 -d 目录是否存在
             9 -e 判断文件或目录是否存在
             10 -x 文件是否可执行
          ### 部分正则表达式()后面可以使用$1,$2,$3来引用
          # return:结束规则并返回状态码给client     
          # rewrite:根据表达式来重定向URI或是修改字符串
          ###Flag标记
               1 last 表示完成rewrite
               2 break 本次匹配完成后,终止匹配
               3 redirect 返回302,临时重定向,浏览器会跳转后URL地址
               4 permanenet 返回301,永久重定向,浏览器会跳转后URL地址
          # set:用于给变量赋值

      location ~* ^.+\.(jpg|jpeg|gif)$ {
        root         /spool/www;
        access_log   off;
        expires      30d;     #控制到期时间
      }
    }
  }
posted @ 2015-07-31 22:38  闫昆  阅读(890)  评论(0编辑  收藏  举报