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


    转自 http://blog.csdn.net/shootyou/article/details/6093562

    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

    [python] view plaincopyprint?
     
    1. 1)pcre安装,支持正则表达式  
    2.   
    3. http://www.pcre.org/  
    4.   
    5. # tar zxvf pcre-7.9.tar.gz  
    6.   
    7. # cd pcre-7.9  
    8.   
    9. #./configure  
    10.   
    11. # make && make install   
    12.    
    13. 2)openssl安装(可选),支持安全协议的站点  
    14.   
    15. http://www.openssl.org/  
    16.   
    17. # tar zxvf openssl-0.9.8l.tar.gz  
    18.   
    19. # cd openssl-0.9.8l  
    20.   
    21. #./config  
    22.   
    23. # make && make install   
    24.   
    25. 3)nginx的安装  
    26.   
    27. # tar zxvf nginx-0.7.64.tar.gz  
    28.   
    29. # cd nginx-0.7.64  
    30.   
    31. 配置安装和不安装组件:--with-MODULE_NAME or --without-MODULE_NAME  
    32.   
    33. # ./configure --prefix=/usr/local/nginx/nginx8011 --with-openssl=/usr/include/openssl --with-http_stub_status_module   
    34.   
    35. # make && make install  
    36.   
    37. 目录结构:  
    38.   
    39. conf 配置文件  
    40.   
    41. html 静态页面  
    42.   
    43. logs 日志文件  
    44.   
    45. sbin 主程序  
    46.   
    47. 4)启动  
    48.   
    49. # /usr/local/nginx/nginx8011/sbin/nginx //启动  
    50.   
    51. 启动参数:  
    52.   
    53. -c </path/to/config> 为 Nginx 指定一个配置文件,来代替缺省的。   
    54.   
    55. -t 不运行,而仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。   
    56.   
    57. -v 显示 nginx 的版本。   
    58.   
    59. -V 显示 nginx 的版本,编译器版本和配置参数。   
    60.   
    61. 不启动,仅测试配置文件:/usr/bin/nginx -t -c ~/mynginx.conf  
    62.   
    63. 5)配置自启动  

    == 一个简单的配置文件 ==

    [python] view plaincopyprint?
     
    1. #-----------------------------------基本模块  
    2.   
    3. # 使用的用户和组  
    4.   
    5. user  www www;  
    6.   
    7. # 指定工作进程数  
    8.   
    9. worker_processes  1;  
    10.   
    11. # 可以使用 [ debug | info | notice | warn | error | crit ]  参数  
    12.   
    13. #error_log  logs/error.log;  
    14.   
    15. #error_log  logs/error.log  notice;  
    16.   
    17. # 指定 pid 存放的路径  
    18.   
    19. #pid        logs/nginx.pid;  
    20.   
    21. #-----------------------------------事件模块   
    22.   
    23. events {  
    24.   
    25. #每个worker的最大连接数  
    26.   
    27.     worker_connections  1024;  
    28.   
    29. }  
    30.   
    31. #-----------------------------------HTTP 模块   
    32.   
    33. http {  
    34.   
    35. #包含一个文件描述了:不同文件后缀对应的MIME,见案例分析  
    36.   
    37.     include       mime.types;  
    38.   
    39. #制定默认MIME类型为二进制字节流  
    40.   
    41.     default_type  application/octet-stream;  
    42.   
    43. #指令 access_log 指派路径、格式和缓存大小。  
    44.   
    45.     #access_log  off;  
    46.   
    47. #开启调用Linux的sendfile(),提供文件传输效率  
    48.   
    49.     sendfile        on;  
    50.   
    51. #是否允许使用socket的TCP_NOPUSH或TCP_CORK选项  
    52.   
    53.     #tcp_nopush     on;  
    54.   
    55.     #指定客户端连接保持活动的超时时间,在这个时间之后,服务器会关掉连接。  
    56.   
    57.     keepalive_timeout  65;  
    58.   
    59. #设置gzip,压缩文件  
    60.   
    61.     #gzip  on;  
    62.   
    63. #为后端服务器提供简单的负载均衡  
    64.   
    65. upstream apaches {  
    66.   
    67. server 127.0.0.1:8001;  
    68.   
    69. server 127.0.0.1:8002;  
    70.   
    71. }  
    72.   
    73. #配置一台虚拟机  
    74.   
    75.     server {  
    76.   
    77.         listen       8012;  
    78.   
    79.         server_name  localhost;  
    80.   
    81.         location / {  
    82.   
    83. proxy_pass http://apaches;  
    84.   
    85.         }  
    86.     }  
    87. }  

    == 模块介绍 ==

    模块划分:

    #Core 核心模块

    #Events 事件模块

    #HTTP HTTP模块

    #Mail 邮件模块

    *核心模块的常用组件

    [python] view plaincopyprint?
     
    1. user   
    2.   
    3. 语法: user user [group]   
    4.   
    5. 缺省值: nobody nobody   
    6.   
    7. 指定Nginx Worker进程运行用户,默认是nobody帐号。  
    8.   
    9. error_log   
    10.   
    11. 语法: error_log file [ debug | info | notice | warn | error | crit ]   
    12.   
    13. 缺省值: ${prefix}/logs/error.log   
    14.   
    15. 制定错误日志的存放位置和级别。  
    16.   
    17. include   
    18.   
    19. 语法: include file | *   
    20.   
    21. 缺省值: none   
    22.   
    23. include 指令还支持像下面配置一样的全局包含的方法,例如包含一个目录下所有以".conf"结尾的文件: include vhosts/*.conf;  
    24.    
    25. pid   
    26.   
    27. 语法: pid file   
    28.   
    29. 进程id存储文件。可以使用 kill -HUP cat /var/log/nginx.pid/ 对Nginx进行配置文件重新加载。   
    30.   
    31. worker_processes   
    32.   
    33. 语法: worker_processes number   
    34.   
    35. 缺省值: 1   
    36.   
    37. 指定工作进程数。nginx可以使用多个worker进程。  

    *事件模块的常用组件

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

    *HTTP模块的核心组件和变量

    [python] view plaincopyprint?
     
    1. 三个作用域:http, server, location   
    2.   
    3. server  
    4.   
    5. 语法:server {...}   
    6.   
    7. 作用域: http   
    8.   
    9. 配置一台虚拟机。  
    10.   
    11. location   
    12.   
    13. 语法: location [=|~|~*|^~] /uri/ { ... }   
    14.   
    15. 作用域: server   
    16.   
    17. 配置访问路径的处理方法。  
    18.   
    19. listen   
    20.   
    21. 语法: listen address:port [ default [ backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bind | ssl ]   
    22.   
    23. 默认值: listen 80   
    24.   
    25. 作用域: server   
    26.   
    27. 指定当前虚拟机的监听端口。  
    28.   
    29. alias   
    30.   
    31. 语法: alias file-path|directory-path;   
    32.   
    33. 作用域: location   
    34.   
    35. 该指令设置指定location使用的路径.注意它跟 root 相似,但是不改变文件的根路径,仅仅是使用文件系统路径   
    36.   
    37. root   
    38.   
    39. 语法: root path   
    40.   
    41. 默认值:root html   
    42.   
    43. 作用域:http, server, location  
    44.   
    45. alias指定的目录是准确的,root是指定目录的上级目录,并且该上级目录要含有location指定名称的同名目录。  
    46.   
    47. 区别:  
    48.   
    49. location /abc/ {  
    50.   
    51. alias /home/html/abc/;  
    52.   
    53. }  
    54.   
    55. 在这段配置下,http://test/abc/a.html就指定的是/home/html/abc/a.html。这段配置亦可改成  
    56.   
    57. location /abc/ {  
    58.   
    59. root /home/html/;  
    60.   
    61. }  
    62.   
    63. 这样,nginx就会去找/home/html/目录下的abc目录了,得到的结果是相同的。  
    64.   
    65. HTTP模块的其他基本组件将结合案例介绍。  
    66.   
    67. 变量:  
    68.   
    69. HTTP header 里边 特定HEADER的值,变量会转成小写,比如 $http_user_agent, $http_referer... header信息 "YOUR-STRANGE-HEADER: values" 能通过 $http_your_strange_header获得.   
    70.   
    71. $arg_PARAMETER   
    72.   
    73. $http_HEADER   
    74.   
    75. $query_string = $args   

    *邮件模块的常用组件(略)

    == 常用场景配置 ==

    1.多台服务器配置负载均衡

    [python] view plaincopyprint?
     
    1. http {  
    2.   
    3.     include       mime.types;  
    4.   
    5.     default_type  application/octet-stream;  
    6.   
    7.     sendfile        on;  
    8.   
    9.     keepalive_timeout  65;  
    10.    
    11. upstream allserver {  
    12.   
    13. #ip_hash;  
    14.   
    15. server 127.0.0.1:8083 down;   
    16.   
    17. server 127.0.0.1:8084 weight=3;   
    18.   
    19. server 127.0.0.1:8001;   
    20.   
    21. server 127.0.0.1:8002 backup;   
    22.   
    23. }  
    24.     server {  
    25.   
    26.         listen       8012;  
    27.   
    28.         server_name  localhost;  
    29.   
    30.         location / {  
    31.   
    32.             proxy_pass http://allserver;  
    33.   
    34.         }  
    35.     }  
    36. }  

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

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

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

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

    2.通过手机客户端的头信息或者请求的参数转发到不用目录

    [python] view plaincopyprint?
     
    1. http {  
    2.   
    3.     include       mime.types;  
    4.   
    5.     default_type  application/octet-stream;  
    6.   
    7.     sendfile        on;  
    8.   
    9.     keepalive_timeout  65;  
    10.   
    11. upstream apaches {  
    12.   
    13. server 127.0.0.1:8001;  
    14.   
    15. server 127.0.0.1:8002;  
    16.   
    17. }  
    18.   
    19. upstream tomcats {  
    20.   
    21. server 127.0.0.1:8083;  
    22.   
    23. server 127.0.0.1:8084;  
    24.   
    25. }  
    26.     server {  
    27.   
    28.         listen       8012;  
    29.   
    30.         server_name  localhost;  
    31.   
    32.         location / {  
    33.   
    34. set $ismob 0;  
    35.   
    36. # 注意if后的空格  
    37.   
    38. if ( $http_chip ~* "(NOKIA3500)|(NOKIA3200)" )  
    39.   
    40. {  
    41.   
    42. set $ismob 1;  
    43.   
    44. proxy_pass http://apaches;  
    45.   
    46. }  
    47.   
    48. if ( $http_chip ~* "(NOKIA3500)|(NOKIA3200)" )  
    49.   
    50. {  
    51.   
    52. set $ismob 1;  
    53.   
    54. proxy_pass http://tomcats;  
    55.   
    56. }  
    57.   
    58.             if ( $ismob = 0 )  
    59.   
    60. {  
    61.   
    62. root /usr/local/nginx/nginx8012/html;  
    63.   
    64. }  
    65.         }  
    66.   
    67. location ~* /rewrite/testXID.jsp {  
    68.   
    69. if ( $arg_XID = "13800138000")  
    70.   
    71. {  
    72.   
    73. rewrite ^(.*)$ http://192.168.0.190:8084/testSID.jsp break;   
    74.   
    75. }  
    76.   
    77. }  
    78.     }  
    79.   
    80. }  

    1、正则表达式匹配,其中:

    = 完全相等;

    ~为区分大小写匹配;

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

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

            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; 

    }

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

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

    3.防盗链

    [python] view plaincopyprint?
     
    1. http {  
    2.   
    3.     include       mime.types;  
    4.   
    5.     default_type  application/octet-stream;  
    6.   
    7.     sendfile        on;  
    8.   
    9.     keepalive_timeout  65;  
    10.   
    11.     server {  
    12.   
    13.         listen       8012;  
    14.   
    15.         server_name  localhost;  
    16.    
    17.         location / {  
    18.   
    19. root html;  
    20.    
    21.         }  
    22.   
    23.         location ~* ^.+/.(gif|jpg|png|swf|flv|rar|zip)$ {   
    24.   
    25. valid_referers none blocked server_names http://localhost baidu.com;   
    26.   
    27. if ($invalid_referer) {   
    28.   
    29.  rewrite ^/ html/50x.html;   
    30.   
    31. }  
    32.   
    33. }  
    34.     }  
    35.   
    36. }  

    4.访问控制:身份验证、限制IP

    [python] view plaincopyprint?
     
    1. http {  
    2.   
    3.     include       mime.types;  
    4.   
    5.     default_type  application/octet-stream;  
    6.   
    7.     sendfile        on;  
    8.   
    9.     keepalive_timeout  65;  
    10.   
    11. upstream tomcats {  
    12.   
    13. server 127.0.0.1:8083;  
    14.   
    15. server 127.0.0.1:8084;  
    16.   
    17. }  
    18.     server {  
    19.   
    20.         listen       8012;  
    21.   
    22.         server_name  localhost;  
    23.   
    24.         location / {  
    25.   
    26. allow 192.168.4.8;  
    27.   
    28. deny all;  
    29.   
    30. auth_basic  "index";  
    31.   
    32. auth_basic_user_file ../htpasswd;  
    33.   
    34. proxy_pass http://tomcats;  
    35.   
    36.         }  
    37.     }  
    38. }  

    cp /usr/local/apache/apache8001/bin/htpasswd /usr/local/bin/

    /usr/local/bin/htpasswd -c htpasswd root

    5.查看Nginx的运行状态

    [python] view plaincopyprint?
     
    1. http {  
    2.   
    3.     include       mime.types;  
    4.   
    5.     default_type  application/octet-stream;  
    6.   
    7.     sendfile        on;  
    8.   
    9.     keepalive_timeout  65;  
    10.   
    11. upstream apaches {  
    12.   
    13. server 127.0.0.1:8001;  
    14.   
    15. server 127.0.0.1:8002;  
    16.   
    17. }  
    18.   
    19. upstream tomcats {  
    20.   
    21. server 127.0.0.1:8083;  
    22.   
    23. server 127.0.0.1:8084;  
    24.   
    25. }  
    26.   
    27.     server {  
    28.   
    29.         listen       8012;  
    30.   
    31.         server_name  localhost;  
    32.   
    33.         location / {  
    34.   
    35. proxy_pass http://tomcats;  
    36.   
    37.         }  
    38.   
    39.         location /NginxStatus {  
    40.   
    41. stub_status on;  
    42.   
    43. access_log  off;  
    44.   
    45. auth_basic  "NginxStatus";  
    46.   
    47. auth_basic_user_file ../htpasswd;  
    48.   
    49.         }  
    50.     }  
    51. }  

    == 进阶内容 ==

    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 

    使用信号加载新的配置

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

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

    limit_zone   limit_conn   limit_rate

    5. 使用Nginx进行地址转发

    rewrite

    nginx rewrite中last和break的区别: http://blog.sina.com.cn/s/blog_4b01279a0100hd4c.html

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

    http://blog.zhuzhaoyuan.com/2009/09/nginx-internals-slides-video/

    == 参考资料 ==

    Nginx中文文档:

    http://wiki.nginx.org/NginxChs

    服务器系统架构分析日志: 

    http://www.sudone.com/

  • 相关阅读:
    Linux内存管理 -- /proc/{pid}/smaps讲解
    link hub(other)
    牛客项目平台管家 | xie_note 学习笔记整理📚 项目来源:https://github.com/Making-It/note ,已获得授权转载
    【Linux】C++后台开发面试
    C++ 后台开发面试时一般考察什么?
    Linux C/C++ 学习路线(已拿腾讯、百度 offer)2
    C++路线图
    【转】C++后台开发校招面试常见问题
    【转】Linux C/C++ 学习路线(已拿腾讯、百度 offer)
    学习经验总结|C++后台开发/云计算方向,offer收割机的学习路线
  • 原文地址:https://www.cnblogs.com/suifengbingzhu/p/3794484.html
Copyright © 2020-2023  润新知