nginx配置安装

Nginx介绍和安装

最全面 Nginx 入门教程 + 常用配置解析

Nginx是一个自由、开源、高性能及轻量级的HTTP服务器及反转代理服务器,

其性能与IMAP/POP3代理服务器相当。Nginx以其高性能、稳定、功能丰富、配置简单及占用系统资源少而著称。

Nginx 超越 Apache 的高性能和稳定性,使得国内使用 Nginx 作为 Web 服务器的网站也越来越多.

基础功能

处理静态文件,索引文件以及自动索引;

反向代理加速(无缓存),简单的负载均衡和容错;

FastCGI,简单的负载均衡和容错;

模块化的结构。过滤器包括gzipping, byte ranges, chunked responses, 以及 SSI-filter 。在SSI过滤器中,到同一个 proxy 或者 FastCGI 的多个子请求并发处理;

SSL 和 TLS SNI 支持;

优势

Nginx专为性能优化而开发,性能是其最重要的考量, 实现上非常注重效率 。它支持内核Poll模型,能经受高负载的考验, 有报告表明能支持高达 50,000 个并发连接数。

Nginx作为负载均衡服务器: Nginx 既可以在内部直接支持 Rails 和 PHP 程序对外进行服务, 也可以支持作为 HTTP代理服务器对外进行服务。

Nginx具有很高的稳定性。其它HTTP服务器,当遇到访问的峰值,或者有人恶意发起慢速连接时,也很可能会导致服务器物理内存耗尽频繁交换,失去响应,只能重启服务器。

例如当前apache一旦上到200个以上进程,web响应速度就明显非常缓慢了。而Nginx采取了分阶段资源分配技术,使得它的CPU与内存占用率非常低。

nginx官方表示保持10,000个没有活动的连接,它只占2.5M内存,就稳定性而言, nginx比lighthttpd更胜一筹。

Nginx支持热部署。它的启动特别容易, 并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够在不间断服务的情况下,对软件版本进行进行升级。

Nginx采用C进行编写, 不论是系统资源开销还是CPU使用效率都比 Perlbal 要好很多。

nginx的安装

开发稳定版: Nginx 0.8.X

当前稳定版: Nginx 0.7.X

历史稳定版: Nginx 0.6.X

  1. pcre安装,支持正则表达式

    http://www.pcre.org/  
      
    # tar zxvf pcre-7.9.tar.gz  
      
    # cd pcre-7.9  
      
    #./configure  
      
    # make && make install   
    
  2. openssl安装(可选),支持安全协议的站点

    http://www.openssl.org/  
      
    # tar zxvf openssl-0.9.8l.tar.gz  
      
    # cd openssl-0.9.8l  
      
    #./config  
      
    # make && make install   
    
  3. nginx的安装

    # tar zxvf nginx-0.7.64.tar.gz  
      
    # cd nginx-0.7.64  
      
    配置安装和不安装组件:--with-MODULE_NAME or --without-MODULE_NAME  
      
    # ./configure --prefix=/usr/local/nginx/nginx8011 --with-openssl=/usr/include/openssl --with-http_stub_status_module   
      
    # make && make install  
    

    目录结构:

    • conf 配置文件

    • html 静态页面

    • logs 日志文件

    • sbin 主程序

一个简单的配置文件

#-----------------------------------基本模块  
  
# 使用的用户和组  
  
user  www www;  
  
# 指定工作进程数  
  
worker_processes  1;  
  
# 可以使用 [ debug | info | notice | warn | error | crit ]  参数  
  
#error_log  logs/error.log;  
  
#error_log  logs/error.log  notice;  
  
# 指定 pid 存放的路径  
  
#pid        logs/nginx.pid;  
  
#-----------------------------------事件模块   
  
events {  
  
#每个worker的最大连接数  
  
    worker_connections  1024;  
  
}  
  
#-----------------------------------HTTP 模块   
  
http {  
  
#包含一个文件描述了:不同文件后缀对应的MIME,见案例分析  
  
    include       mime.types;  
  
#制定默认MIME类型为二进制字节流  
  
    default_type  application/octet-stream;  
  
#指令 access_log 指派路径、格式和缓存大小。  
  
    #access_log  off;  
  
#开启调用Linux的sendfile(),提供文件传输效率  
  
    sendfile        on;  
  
#是否允许使用socket的TCP_NOPUSH或TCP_CORK选项  
  
    #tcp_nopush     on;  
  
    #指定客户端连接保持活动的超时时间,在这个时间之后,服务器会关掉连接。  
  
    keepalive_timeout  65;  
  
#设置gzip,压缩文件  
  
    #gzip  on;  
  
#为后端服务器提供简单的负载均衡  
  
upstream apaches {  
  
server 127.0.0.1:8001;  
  
server 127.0.0.1:8002;  
  
}  
  
#配置一台虚拟机  
  
    server {  
  
        listen       8012;  
  
        server_name  localhost;  
  
        location / {  
  
proxy_pass http://apaches;  
  
        }  
    }  
}  

模块介绍

模块划分:

  • Core 核心模块

  • Events 事件模块

  • HTTP HTTP模块

  • Mail 邮件模块

核心模块的常用组件

语法: worker_processesuser   
  
语法: user user [group]   
  
缺省值: nobody nobody   
  
指定Nginx Worker进程运行用户,默认是nobody帐号。  
  
error_log   
  
语法: error_log file [ debug | info | notice | warn | error | crit ]   
  
缺省值: ${prefix}/logs/error.log   
  
制定错误日志的存放位置和级别。  
  
include   
  
语法: include file | *   
  
缺省值: none   
  
include 指令还支持像下面配置一样的全局包含的方法,例如包含一个目录下所有以".conf"结尾的文件: include vhosts/*.conf;  
   
pid   
  
语法: pid file   
  
进程id存储文件。可以使用 kill -HUP cat /var/log/nginx.pid/ 对Nginx进行配置文件重新加载。   
  
worker_processes    number   
  
缺省值: 1   
  
指定工作进程数。nginx可以使用多个worker进程。  

事件模块的常用组件

worker_connections   
  
语法:worker_connections number   
  
通过worker_connections和worker_proceses可以计算出maxclients: max_clients = worker_processes * worker_connections  
  
作为反向代理,max_clients为: max_clients = worker_processes * worker_connections/4 ,因为浏览器访问时会通过连接池建立多个连接。  
  
use   
  
语法:use [ kqueue | rtsig | epoll | /dev/poll | select | poll | eventport ]   
  
如果在./configure的时候指定了不止一种事件模型,那么可以设置其中一个,以便告诉nginx使用哪种事件模型。默认情况下nginx会在./configure时找出最适合系统的事件模型。  
  
事件模型是指Nginx处理连接的方法。  

HTTP模块的核心组件和变量

三个作用域:http, server, location   
  
server  
  
语法:server {...}   
  
作用域: http   
  
配置一台虚拟机。  
  
location   
  
语法: location [=|~|~*|^~] /uri/ { ... }   
  
作用域: server   
  
配置访问路径的处理方法。  
  
listen   
  
语法: listen address:port [ default [ backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bind | ssl ]   
  
默认值: listen 80   
  
作用域: server   
  
指定当前虚拟机的监听端口。  
  
alias   
  
语法: alias file-path|directory-path;   
  
作用域: location   
  
该指令设置指定location使用的路径.注意它跟 root 相似,但是不改变文件的根路径,仅仅是使用文件系统路径   
  
root   
  
语法: root path   
  
默认值:root html   
  
作用域:http, server, location  
  
alias指定的目录是准确的,root是指定目录的上级目录,并且该上级目录要含有location指定名称的同名目录。  
  
区别:  
  
location /abc/ {  
  
alias /home/html/abc/;  
  
}  
  
在这段配置下,http://test/abc/a.html就指定的是/home/html/abc/a.html。这段配置亦可改成  
  
location /abc/ {  
  
root /home/html/;  
  
}  
  
这样,nginx就会去找/home/html/目录下的abc目录了,得到的结果是相同的。  
  
HTTP模块的其他基本组件将结合案例介绍。  
  
变量:  
  
HTTP header 里边 特定HEADER的值,变量会转成小写,比如 $http_user_agent, $http_referer... header信息 "YOUR-STRANGE-HEADER: values" 能通过 $http_your_strange_header获得.   
  
$arg_PARAMETER   
  
$http_HEADER   
  
$query_string = $args   

常用场景配置

  1. 多台服务器配置负载均衡
http {  
 
   include       mime.types;  
 
   default_type  application/octet-stream;  
 
   sendfile        on;  
 
   keepalive_timeout  65;  
  
upstream allserver {  
 
#ip_hash;  
 
server 127.0.0.1:8083 down;   
 
server 127.0.0.1:8084 weight=3;   
 
server 127.0.0.1:8001;   
 
server 127.0.0.1:8002 backup;   
 
}  
   server {  
 
       listen       8012;  
 
       server_name  localhost;  
 
       location / {  
 
           proxy_pass http://allserver;  
 
       }  
   }  
}  

ip_hash; nginx中的ip_hash技术能够将某个ip的请求定向到同一台后端,这样一来这个ip下的某个客户端和某个后端就能建立起稳固的session

  • down 表示单前的 server 暂时不参与负载

  • weight 默认为 1.weight 越大,负载的权重就越大。

  • backup: 其它所有的非 backup 机器 down 或者忙的时候,请求 backup机器。所以这台机器压力会最轻。

  1. 通过手机客户端的头信息或者请求的参数转发到不用目录
http {  
  
    include       mime.types;  
  
    default_type  application/octet-stream;  
  
    sendfile        on;  
  
    keepalive_timeout  65;  
  
upstream apaches {  
  
server 127.0.0.1:8001;  
  
server 127.0.0.1:8002;  
  
}  
  
upstream tomcats {  
  
server 127.0.0.1:8083;  
  
server 127.0.0.1:8084;  
  
}  
    server {  
  
        listen       8012;  
  
        server_name  localhost;  
  
        location / {  
  
set $ismob 0;  
  
# 注意if后的空格  
  
if ( $http_chip ~* "(NOKIA3500)|(NOKIA3200)" )  
  
{  
  
set $ismob 1;  
  
proxy_pass http://apaches;  
  
}  
  
if ( $http_chip ~* "(NOKIA3500)|(NOKIA3200)" )  
  
{  
  
set $ismob 1;  
  
proxy_pass http://tomcats;  
  
}  
  
            if ( $ismob = 0 )  
  
{  
  
root /usr/local/nginx/nginx8012/html;  
  
}  
        }  
  
location ~* /rewrite/testXID.jsp {  
  
if ( $arg_XID = "13800138000")  
  
{  
  
rewrite ^(.*)$ http://192.168.0.190:8084/testSID.jsp break;   
  
}  
  
}  
    }  
  
}  
  • 正则表达式匹配,其中:

    = 完全相等;

    ~为区分大小写匹配;

    ~*为不区分大小写匹配;

    !和!*分别为区分大小写不匹配及不区分大小写不匹配。

    ​ 2、文件及目录匹配,其中:

    -f和!-f用来判断是否存在文件;

    -d和!-d用来判断是否存在目录;

    -e和!-e用来判断是否存在文件或目录;

    -x和!-x用来判断文件是否可执行。

    if (-d $request_filename){ ... }

  • 哪些地方会出现正则表达式:

    1.location ~* /.(gif|jpg|png|swf|flv)${...}

    2.rewrite ^(.*)$ /nginx-ie/$1 break;

  • 正则表达式举例:

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

    if ($host ~* (.*)/.domain/.com) {

    set $sub_name $1;

    rewrite ^/sort//(/d+)//?$ /index.php?act=sort&cid=$sub_name&id=$1 last;

    }

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

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

    1. 防盗链

      http {  
        
          include       mime.types;  
        
          default_type  application/octet-stream;  
        
          sendfile        on;  
        
          keepalive_timeout  65;  
        
          server {  
        
              listen       8012;  
        
              server_name  localhost;  
         
              location / {  
        
      root html;  
         
              }  
        
              location ~* ^.+/.(gif|jpg|png|swf|flv|rar|zip)$ {   
        
      valid_referers none blocked server_names http://localhost baidu.com;   
        
      if ($invalid_referer) {   
        
       rewrite ^/ html/50x.html;   
        
      }  
        
      }  
          }  
        
      }  
      
    2. 访问控制:身份验证、限制IP

      http {  
        
          include       mime.types;  
        
          default_type  application/octet-stream;  
        
          sendfile        on;  
        
          keepalive_timeout  65;  
        
      upstream tomcats {  
        
      server 127.0.0.1:8083;  
        
      server 127.0.0.1:8084;  
        
      }  
          server {  
        
              listen       8012;  
        
              server_name  localhost;  
        
              location / {  
       cp /usr/local/apache/apache8001/bin/htpasswd /usr/local/bin/
      /usr/local/bin/htpasswd -c htpasswd root
       
      allow 192.168.4.8;  
        
      deny all;  
        
      auth_basic  "index";  
        
      auth_basic_user_file ../htpasswd;  
        
      proxy_pass http://tomcats;  
        
              }  
          }  
      }  
      
      cp /usr/local/apache/apache8001/bin/htpasswd /usr/local/bin/
      /usr/local/bin/htpasswd -c htpasswd root
      
    3. 查看Nginx的运行状态

      http {  
        
          include       mime.types;  
        
          default_type  application/octet-stream;  
        
          sendfile        on;  
        
          keepalive_timeout  65;  
        
      upstream apaches {  
        
      server 127.0.0.1:8001;  
        
      server 127.0.0.1:8002;  
        
      }  
        
      upstream tomcats {  
        
      server 127.0.0.1:8083;  
        
      server 127.0.0.1:8084;  
        
      }  
        
          server {  
        
              listen       8012;  
        
              server_name  localhost;  
        
              location / {  
        
      proxy_pass http://tomcats;  
        
              }  
        
              location /NginxStatus {  
        
      stub_status on;  
        
      access_log  off;  
        
      auth_basic  "NginxStatus";  
        
      auth_basic_user_file ../htpasswd;  
        
              }  
          }  
      }  
      

进阶内容

  1. 查看Nginx的运行状态

    Active connections: 364

    server accepts handled requests

    5477919 5477919 17515830

    Reading: 10 Writing: 26 Waiting: 328

    意思如下:

    active connections – 当前 Nginx 正处理的活动连接数。

    serveraccepts handled requests -- 总共处理了 5477919 个连接 , 成功创建 5477919 次握手 (证明中间没有失败的 ), 总共处理了 17515830 个请求 ( 平均每次握手处理了 3.2 个数据请求 )。

    reading -- nginx 读取到客户端的 Header 信息数。

    writing -- nginx 返回给客户端的 Header 信息数。

    waiting -- 开启 keep-alive 的情况下,这个值等于 active - (reading + writing),意思就是 Nginx 已经处理完正在等候下一次请求指令的驻留连接。

  2. 案例分析:

    将web server由apache换为nginx后,却带来意想不到的问题.多个页面显示模块显示"正在加载中..."然后一直停顿,使用FireBug调试前端,XSL文件解析失败.但载入又是HTTP 200 的正常状态.

    继续用FireBug调试,发现XSL文件下载时的HTTP响应头中,

    Content-Type是oct/stream ,而在原来的apache中,是text/xml,于是修改/etc/nginx/mime.types文件.将XSL的扩展名加到xml组中.问题解决.

  3. 通过系统的信号控制 Nginx

使用信号加载新的配置

平滑升级到新的二进制代码

  1. 使用Nginx限制下载速率和并发数

    limit_zone limit_conn limit_rate

  2. 使用Nginx进行地址转发

    rewrite

    nginx rewrite中last和break的区别

  3. Nginx Internals: Nginx源代码、内部机制的分析

参考资料

Nginx中文文档

服务器系统架构分析日志

使用 Nginx 提升网站访问速度

原文地址:https://www.cnblogs.com/we9999/p/11756900.html