---
title: "nginx的配置及使用"
author: "g21121"
date: "2012-02-09T13:59:10Z"
tags: []
categories: ["企业架构"]
slug: "nginx"
draft: false
lastmod: "2012-02-15T14:10:44Z"
id: 1399403
url: "https://286.iteye.com/blog/1399403"
---

Nginx ("engine x") 是一个高性能的 HTTP和反向代理服务器，据说他可以同时处理10万的并发访问量，这个我就没法确认了。  
Nginx官方地址是：[http://nginx.org](http://nginx.org)  
上面提供了windows和unix版本的nginx，有稳定版也有开发板，可以根据具体情况选择。  
现在开始我们的nginx之旅吧！  
首先，从nginx下载了windows版本的压缩包，解压后看到  
![](http://dl.iteye.com/upload/attachment/0062/9352/3d6152c0-74a9-34f6-a91f-8e39e506774a.jpg)

这样的目录结构，熟悉apache的朋友应该很快就明白各个目录的作用。比较重要的就是conf和html这两个文件夹，html是默认放置网站内容的文件夹，conf是配置文件放置的地方，打开conf发现  
![](http://dl.iteye.com/upload/attachment/0062/9354/75dc3d56-38cd-372c-a7ff-a7b20d467ca5.jpg)

但是貌似只有fastcgi.conf和nginx.conf可以编辑。  
打开nginx.conf文件：

```
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

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

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # 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;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

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


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

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

    #    ssl_session_timeout  5m;

    #    ssl_protocols  SSLv2 SSLv3 TLSv1;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers   on;

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

}
```

 初学者看见这些可能已经头疼了，熟悉apache配置的朋友估计笑了。  
我们就找几个重要的说说吧（当然想要让配置生效要先去掉前面的#号）：

```
#linux/unix下那个用户运行nginx
user  nobody; 
#进程运行数量，根据cpu数量或其他需求配置
worker_processes  1; 
#错误日志
error_log  logs/error.log;
error_log  logs/error.log  notice;
error_log  logs/error.log  info;
#nginx的pid配置 pid百度百科：http://baike.baidu.com/view/402830.htm#2
pid        logs/nginx.pid;

#每个进程的最大连接数量，最大连接数量=worker_processes*worker_connections
events {
    worker_connections  1024;
}

http {
	#mime类型配置，mime百度百科：http://baike.baidu.com/view/160611.htm
    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  logs/access.log  main;
	#sendfile 指令指定 nginx 是否调用 sendfile 函数（zero copy 方式）来输出文件，对于普通应用，必须设为 on,如果用来进行下载等应用磁盘IO重负载应用，可设置为 off，以平衡磁盘与网络I/O处理速度，降低系统的uptime.
    sendfile        on;
    #tcp_nopush配置，tcp_nopush和tcp_nodelay开启可以提高nginx性能，具体作用：http://www.oschina.net/question/17_2516
    tcp_nopush     on;
	#连接活动时间，即超时时间
    keepalive_timeout  65;
	#压缩传输，gzip百度百科：http://baike.baidu.com/view/966625.htm
    gzip  on;
	#服务配置
    server {
    	#监听端口，即什么端口可以访问到nginx，与tomcat，apache一样
        listen       80;
        #服务器名称
        server_name  localhost;
		#文字编码
        charset koi8-r;

        access_log  logs/host.access.log  main;

        location / {
        	#默认网页放置位置，就是我们上面说到的html文件夹
            root   html;
            #主页，类似于<welcome-file-list>
            index  index.html index.htm;
        }
		#错误页面
        error_page  404              /404.html;

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # 设置php代理，即php处理服务器，比如127.0.0.1:80是apache服务器，就交由apache处理php的请求
        
        location ~ \.php$ {
        	#代理服务器地址，eg:http://127.0.0.1:8080,端口为80，"80"可省略
            proxy_pass   http://127.0.0.1;
        }

        #php FastCGI服务器的一些配置
        location ~ \.php$ {
            root           html;
            #定义解析php程序使用的FastCGI接口
            fastcgi_pass   127.0.0.1:9000;
            #php首页
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi_params;
        }

        location ~ /\.ht {
            deny  all;
        }
    }


    # 第一台虚拟主机，当需要用到多台虚拟住址的时候，只有复制server{}中的内容就可以了
    
    server {
        listen       8000;
        listen       somename:8080;
        server_name  somename  alias  another.alias;

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


    # HTTPS 服务器
    
    server {
        listen       443;
        server_name  localhost;

        ssl                  on;
        ssl_certificate      cert.pem;
        ssl_certificate_key  cert.key;

        ssl_session_timeout  5m;

        ssl_protocols  SSLv2 SSLv3 TLSv1;
        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers   on;

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

 在windows下启动nginx非常简单，运行nginx.exe就可以了，打开测试地址：[http://127.0.0.1](http://127.0.0.1)看看是否显示了nginx的欢迎页，显示说明已经成功启动。

下面说下linux下安装nginx：  
linux下安装nginx需要PCRE的支持，PCRE：[http://www.pcre.org/](http://www.pcre.org/)，按照网站上的指导安装即可。

安装之前可以先删除已经安装的低版本的pcre：

```
#查找已安装的pcre
rpm -qa|grep pcre
#显示结果为：pcre-6.6-2.el5_1.7
#在删除系统自带的PCRE之前，要先备份一下libpcre.so.0这个文件，rpm有关联性，当强制删除pcre时libpcre.so.0也会被删除，这样就会导致新的pcre安装不上，不信你可以试试
cp /lib/libpcre.so.0 /home/g21121/
#删除pcre
rpm -e --nodeps pcre-6.6-2.el5_1.7
```

 

然后安装新的pcre：

```
#赋予执行权限
chmod 755 pcre-8.30
#解压pcre
tar -zxvf pcre-8.30 
#进入pcre目录
cd pcre-8.30
#拷贝libpcre.so.0到lib
cp /home/g21121/libpcre.so.0 /lib/
#采用默认路径就可以，避免没必要的麻烦
./configure
#编译
make
#安装
make install
```

   安装pcre 注意执行顺序，先拷贝再删除，再拷贝再安装，这样就成功了。

   安装完成后，我们开始安装nginx：

```
./configure --without-http_rewrite_module --without-http_gzip_module
make
make install
```

 安装完成，如果安装过程中遇到错误，可以根据提示增加configure后面的参数即可，下面是configure的参数列表：

./configure --help 写道

 –prefix=&lt;path&gt; - 安装路径，如果没有指定，默认为/usr/local/nginx。

–sbin-path=&lt;path&gt; - nginx可执行命令的文件，如果没有指定，默认为&lt;prefix&gt;/sbin/nginx。

–conf-path=&lt;path&gt; - 在没有使用-c参数指定的情况下nginx.conf的默认位置，如果没有指定，默认为&lt;prefix&gt;/conf/nginx.conf。

–pid-path=&lt;path&gt; - nginx.pid的路径，如果没有在nginx.conf中通过“pid”指令指定，默认为&lt;prefix&gt;/logs/nginx.pid。

–lock-path=&lt;path&gt; - nginx.lock文件路径，如果没有指定，默认为&lt;prefix&gt;/logs/nginx.lock。

–error-log-path=&lt;path&gt; - 当没有在nginx.conf中使用“error\_log”指令指定时的错误日志位置，如果没有指定，默认为&lt;prefix&gt;/logs/error.log。

–http-log-path=&lt;path&gt; - 当没有在nginx.conf中使用“access\_log”指令指定时的访问日志位置，如果没有指定，默认为&lt;prefix&gt;/logs/access.log。

–user=&lt;user&gt; - 当没有在nginx.conf中使用“user”指令指定时nginx运行的用户，如果没有指定，默认为“nobody”。

–group=&lt;group&gt; - 当没有在nginx.conf中使用“user”指令指定时nginx运行的组，如果没有指定，默认为“nobody”。

–builddir=DIR - 设置构建目录。

–with-rtsig\_module - 启用rtsig模块。

–with-select\_module –without-select\_module - 如果在configure的时候没有发现kqueue, epoll, rtsig或/dev/poll其中之一，select模块始终为启用状态。

–with-poll\_module –without-poll\_module - 如果在configure的时候没有发现kqueue, epoll, rtsig或/dev/poll其中之一，poll模块始终为启用状态。

–with-http\_ssl\_module - 启用ngx\_http\_ssl\_module，启用SSL支持并且能够处理HTTPS请求。需要OpenSSL，在Debian系统中，对应的包为libssl-dev。

–with-http\_realip\_module - 启用ngx\_http\_realip\_module

–with-http\_addition\_module - 启用ngx\_http\_addition\_module

–with-http\_sub\_module - 启用ngx\_http\_sub\_module

–with-http\_dav\_module - 启用ngx\_http\_dav\_module

–with-http\_flv\_module - 启用ngx\_http\_flv\_module

–with-http\_stub\_status\_module - 启用”server status”（服务状态）页

–without-http\_charset\_module - 禁用ngx\_http\_charset\_module

–without-http\_gzip\_module - 禁用ngx\_http\_gzip\_module，如果启用，需要zlib包。

–without-http\_ssi\_module - 禁用ngx\_http\_ssi\_module

–without-http\_userid\_module - 禁用ngx\_http\_userid\_module

–without-http\_access\_module - 禁用ngx\_http\_access\_module

–without-http\_auth\_basic\_module - 禁用ngx\_http\_auth\_basic\_module

–without-http\_autoindex\_module - 禁用ngx\_http\_autoindex\_module

–without-http\_geo\_module - 禁用ngx\_http\_geo\_module

–without-http\_map\_module - 禁用ngx\_http\_map\_module

–without-http\_referer\_module - 禁用ngx\_http\_referer\_module

–without-http\_rewrite\_module - 禁用ngx\_http\_rewrite\_module。如果启用，需要PCRE包。

–without-http\_proxy\_module - 禁用ngx\_http\_proxy\_module

–without-http\_fastcgi\_module - 禁用ngx\_http\_fastcgi\_module

–without-http\_memcached\_module - 禁用ngx\_http\_memcached\_module

–without-http\_limit\_zone\_module - 禁用ngx\_http\_limit\_zone\_module

–without-http\_empty\_gif\_module - 禁用ngx\_http\_empty\_gif\_module

–without-http\_browser\_module - 禁用ngx\_http\_browser\_module

–without-http\_upstream\_ip\_hash\_module - 禁用ngx\_http\_upstream\_ip\_hash\_module

–with-http\_perl\_module - 启用ngx\_http\_perl\_module

–with-perl\_modules\_path=PATH - 为perl模块设置路径

–with-perl=PATH - 为perl库设置路径

–http-client-body-temp-path=PATH - 为http连接的请求实体临时文件设置路径，如果没有指定，默认为&lt;prefix&gt;/client\_body\_temp

–http-proxy-temp-path=PATH - 为http代理临时文件设置路径，如果没有指定，默认为&lt;prefix&gt;/proxy\_temp

–http-fastcgi-temp-path=PATH - 为http fastcgi临时文件设置路径，如果没有指定，默认为&lt;prefix&gt;/fastcgi\_temp

–without-http - 禁用HTTP服务

–with-mail - 启用IMAP4/POP3/SMTP代理模块

–with-mail\_ssl\_module - 启用ngx\_mail\_ssl\_module

–with-cc=PATH - 设置C编译器路径

–with-cpp=PATH - 设置C预处理器路径

–with-cc-opt=OPTIONS - 变量CFLAGS中附加的参数，用于FreeBSD中的PCRE库，同样需要指定–with-cc-opt=”-I /usr/local/include”，如果我们使用select()函数则需要同时增加文件描述符数量，可以通过–with-cc-opt=”-D FD\_SETSIZE=2048”指定。

–with-ld-opt=OPTIONS - 通过连接器的附加参数，用于FreeBSD中的PCRE库，同样需要指定–with-ld-opt=”-L /usr/local/lib”。

–with-cpu-opt=CPU - 指定编译的CPU，可用的值为: pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64

–without-pcre - 禁用PCRE库文件，同时将禁用HTTP rewrite 模块，如果要在”location”指令中使用正则表达式，同样需要PCRE库。

–with-pcre=DIR - 设置PCRE库源文件路径。

–with-pcre-opt=OPTIONS - 在编译时为PCRE设置附加参数。

–with-md5=DIR - 设置md5库源文件路径。

–with-md5-opt=OPTIONS - 在编译时为md5设置附加参数。

–with-md5-asm - 使用md5汇编源。

–with-sha1=DIR - 设置sha1库源文件路径。

–with-sha1-opt=OPTIONS - 在编译时为sha1设置附加参数。

–with-sha1-asm - 使用sha1汇编源。

–with-zlib=DIR - 设置zlib库源文件路径。

–with-zlib-opt=OPTIONS - 在编译时为zlib设置附加参数。

–with-zlib-asm=CPU - 为指定的CPU使用zlib汇编源进行优化，可用值为: pentium, pentiumpro。

–with-openssl=DIR - 设置openssl库源文件路径。

–with-openssl-opt=OPTIONS - 在编译时为openssl设置附加参数。

–with-debug - 启用debug记录。

–add-module=PATH - 增加一个在PATH中的第三方模块。