Nginx user guide

本文详细介绍Nginx的特点、安装步骤及配置方法,并提供了多种应用场景下的配置实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

== 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 主程序

4)启动

# /usr/local/nginx/nginx8011/sbin/nginx //启动

启动参数:

-c </path/to/config> 为 Nginx 指定一个配置文件,来代替缺省的。 

-t 不运行,而仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。 

-v 显示 nginx 的版本。 

-V 显示 nginx 的版本,编译器版本和配置参数。 

不启动,仅测试配置文件:/usr/bin/nginx -t -c ~/mynginx.conf

5)配置自启动


样例配置文件

#user  nobody;
worker_processes  4;

error_log   /usr/local/nginx-1.6.0/logs/error.log;
error_log   /usr/local/nginx-1.6.0/logs/error.log  notice;
error_log   /usr/local/nginx-1.6.0/logs/error.log  info;

pid        /usr/local/nginx-1.6.0/logs/nginx.pid;
worker_rlimit_nofile 51200;

events {
     #设置模式
    use epoll;
    worker_connections  51200;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    
    #日志格式
    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  /usr/local/nginx-1.6.0/logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  60;

    gzip  on;
    gzip_min_length  1k;
    gzip_buffers 4 16k; #按照原始数据大小以16k为单位的4倍申请内存
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types  text/plan application/x-javascript text/css application/xml;
    gzip_vary on;
    
    #允许客户端最大单个文件字节数
    client_max_body_size 300m;
    #缓冲区代理缓冲用户端请求的最大字节数,类似现保存在本地再传给用户
    client_body_buffer_size 128k;
    #与后端服务器连接的超时时间_发起握手等候响应超时时间
    proxy_connect_timeout  600;
    #连接成功后等待后端服务器响应时间_已经进入后端排队之中等待处理
    proxy_read_timeout  600;
    #后端服务器数据回传时间_即规定时间内后端服务器必须传完所有数据
    proxy_send_timeout  600;
    #代理请求缓冲区_此缓冲区会保存请求头信息工Nginx进行规则处理_一般只要能保存下头信息即可
    proxy_buffer_size  16k;
    #同上 告诉Nginx保存单个用的几个Buffer最大用多少空间
    proxy_buffers 4 32k;
    #如何系统很忙可以申请更大的proxy_buffers 官方推荐*2
    proxy_busy_buffers_size  64k;
    #proxy临时缓冲大小
    proxy_temp_file_write_size 64k;
    
    
    #tomcat config
    upstream tomcat_server{
      server 127.0.0.1:8888 ;
    }
    
    server {
        access_log  /usr/local/nginx-1.6.0/logs/$server_name.log  main;
        listen       8088;
        server_name  localhost    vm-09b7-b009.apac.nsroot.net;
        index index.html index.htm index.jsp default.jsp index.do default.do;
        root   html;
        
        ####location用法
        #location ~ 表示区分大小写的匹配; location ~* 表示区分大小写的匹配; 
        #^~ 表示禁止匹配到字符串后再去检查正则表达式; = 可以进行精确匹配
        
        #location = / {
        #    #仅仅匹配 /
        #    [configuration A]
        #}
        
        #location / {
        #    #匹配任何以 / 开头的查询,但正则表达式及较长的字符串(例如/admin/)将优先匹配
        #    [configration B]
        #}
        
        #location ^~ /images/ {
        #    #匹配任何以 /images/ 开头的字符串,并且停止搜索,所以正在表达式将不会被检查
        #    [configration C]
        #}
        
        #location ~* \.(gif|jpg|jpeg)$ {
        #    #匹配以.gif .jpg .jpeg 结尾的任何请求,但是/images/内的请求将使用configuration C 的配置
        #    [configuration D]
        #}
        
        #请求匹配结果
        # /  -> configuration A
        # /documents/document.html -> configuration B
        # /images/1.gif ->configuration C
        # /document/1.gif ->configuration D
        
        #root用法
        #例如 location /i/ { root /spool/w3;}时, 请求url地址"/i/top.gif" 将返回文件 "/spool/w3/top.gif" 的内容给客户端
        
        
        #tomcat结合做反向代理
        location ~ \.(jsp|jspx|do)?$
        {
           proxy_set_header Host $host;
           proxy_set_header X-Forwarded-For $remote_addr;
           proxy_pass http://tomcat_server;
        }
        
        #常见格式flash.图片浏览器本地缓存30天, js,css浏览器本地缓存1h
         location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$  {
              expires 30d;
            }
        location ~ .*\.(js|css)$  {
              expires 1h;
            }
            
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        
        # 结合Memcached,访问以/cache开始的uri,则读取以uri为key的memcached缓存内存,显示给用户,如果key不存在,则重定向到
        location /cache/  {
            memcached_buffer_size 10240;
            set $memcached_key  $request_uri;
            memcached_pass  127.0.0.1:11211;
            default_type  text/html;
            error_page  404 @fallback;
        }
        
        location @fallback {
            proxy_pass  backend;
        }
        #error_page  404              /404.html;
       
        #charset utf-8;

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
    
   
   #server{
   #    listen      8080;
   #    server_name  localhost    vm-09b7-b009.apac.nsroot.net;
   #    index index.html index.htm index.jsp default.jsp index.do default.do;
   #    root  /data0/htdocs/www;
   #    
   #    #if(-d $request_filename)
   #    #{
   #    #     rewrite ^/(.*)([^/])$ http://$host/$1$2/permanent;
   #    #}        
   #
   #    location ~ \.(jsp|jspx|do)?$
   #    {
   #       proxy_set_header Host $host;
   #       proxy_set_header X-Forwarded-For $remote_addr;
   #       proxy_pass http://tomcat_server;
   #    }
   #    
   #    #常见格式flash.图片浏览器本地缓存30天, js,css浏览器本地缓存1h
   #     location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$  {
   #          expires 30d;
   #        }
   #
   #    location ~ .*\.(js|css)$  {
   #          expires 1h;
   #        }
   #        
   #    access_log off;
   #}



    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    
    # mail {
    #    auth_http  127.0.0.1:80/auth.php;
    #    pop3_capabilities  "TOP"  "USER";
    #    imap_capabilities  "IMAP4rev1"  "UIDPLUS";

    #   server {
    #        listen     110;
    #        protocol   pop3;
    #        proxy      on;
    #    }
    #    server {
    #        listen      25;
    #        protocol    smtp;
    #        proxy       on;
    #        smtp_auth   login plain;
    #        xclient     off;
    #    }
    # }

}





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

#-----------------------------------基本模块

# 使用的用户和组

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 邮件模块



*核心模块的常用组件

user 

语法: 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 

语法: 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

 

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

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

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

 

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

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; 

}

}
    }

}

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.防盗链

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; 

}

}
    }

}

 

4.访问控制:身份验证、限制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 / {

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


5.查看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 

使用信号加载新的配置

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

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/

使用 Nginx 提升网站访问速度: 

http://www.ibm.com/developerworks/cn/web/wa-lo-nginx/

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值