码迷,mamicode.com
首页 > 其他好文 > 详细

nginx详细配置教程

时间:2014-05-27 03:53:54      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:nginx 服务器 linux

一.安装nginx

安装nginx之前首先需要安装"Development Tools"和 "Development Libraries"两个基本组包。yum groupinstall "Development Tools" "Development Libraries"。另外还需要安装pcre-devel包。

安装pcre-devel:

   yum install pcre-devel

安装nginx:

   添加nginx账号groupadd -g 4000 nginx;useradd -g 4000 -u 4000 nginx -s /sbin/nologin

./configure     --prefix=/usr/local/nginx     --sbin-path=/usr/local/nginx/sbin/nginx     --conf-path=/etc/nginx/nginx.conf     --error-log-path=/var/log/nginx/error.log     --http-log-path=/var/log/nginx/access.log     --pid-path=/var/run/nginx/nginx.pid      --lock-path=/var/lock/nginx.lock     --user=nginx     --group=nginx     --with-http_ssl_module     --with-http_flv_module     --with-http_stub_status_module     --with-http_gzip_static_module     --http-client-body-temp-path=/var/tmp/nginx/client/     --http-proxy-temp-path=/var/tmp/nginx/proxy/     --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/     --with-pcre
    make
    make install
    这下可以启动nginx了。执行/usr/local/ngin/sbin/nginx会报错因为我们需要事先创建上面编译的时候需要的目录。
    mkdir -p /var/tmp/nginx/client/
    mkdir -p /var/tmp/nginx/proxy/
    mkdir -p /var/tmp/nginx/fcgi/

再次执行上述命令后执行netstat -tunpl | grep 80发现nginx已经监听在tcp的80端口上了。


二.为nginx提供SysV init脚本:

新建文件/etc/rc.d/init.d/nginx内容如下

#!/bin/bash
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse #               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs() {
   # make required directories
   user=`nginx -V 2>&1 | grep "configure arguments:" | sed ‘s/[^*]*--user=\([^ ]*\).*/\1/g‘ -`
   options=`$nginx -V 2>&1 | grep ‘configure arguments:‘`
   for opt in $options; do
       if [ `echo $opt | grep ‘.*-temp-path‘` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
restart() {
    configtest || return $?
    stop
    sleep 1
    start
}
reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}
force_reload() {
    restart
}
configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
    status $prog
}
rh_status_q() {
    rh_status >/dev/null 2>&1
}
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

而后为此脚本赋予执行权限chmod +x /etc/rc.d/init.d/nginx

添加至服务管理列表并让其开机自动启动

chkconfig --add nginx

chkconfig nginx on

service nginx reload重新加载nginx


三.nginx基本配置文件介绍  

#user  nobody;  //定义Nginx运行的用户和用户组
worker_processes  1;  //Nginx运行时的工作进程数
#error_log  logs/error.log;  //错误日志,nginx的日志可以直接发给远程服务器
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events { //用来设置影响nginx工作属性和连接数上线的总配置
    use epoll;//使用基于epoll的事件驱动模型
    worker_connections  1024; //每一个work进程连接数的限制根据服务器的带宽和脚本的大小来评估
    worker_cpu_affinity 0001 0100; //将wock进程绑定在第一颗和第四颗cpu上这是以掩码的方式来计算的
    worker_rlimit_nofile 51200;//限定nginx最多能够打开的文件数也可以在limits.conf文件中配置
    worker_priority_number -10; //定义work进程的优先级取值为-20到20默认为0。给进程一样值越低优先级越高
}
http {
    include       mime.types;
    default_type  application/octet-stream; //默认的mime类型
    #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; //访问日志的位置access_log off可以关闭访问日志
    sendfile        on; //服务器应该开启的功能可以避免将数据转到应用程序进程做转换
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65; #长连接的超时时间应该设置的小点例如5
    #gzip  on; //开启gzip压缩功能
    server {  //虚拟主机的设置
        listen       80; //监听的端口
        server_name  localhost; //主机的名称
        #charset koi8-r; //设置字符集
        #access_log  logs/host.access.log  main; //设置访问日志
        location / {
            root   html;  //定义网页文件目录可以使用绝对路径不使用绝对路径的时候--prefix的选项作为相对路径
            index  index.html index.htm; //该url下的默认访问文件
        }
        #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;
    #    }  
    #} 
}


四.nginx虚拟主机配置

server {
    listen       127.0.0.1:80;
    server_name  www.qiguo1.com;
    location / {
        root /web/htmlone
        index index.html
    }
}
server{
    listen       127.0.0.1:80;
    server_name  www.qiguo2.com;
   location / {
       root /web/htmltwo
       index index.html
   }
}

在/etc/hosts文件中输入

127.0.0.1     www.qiguo1.com

127.0.0.1     www.qiguo2.com

在/web/htmlone和/web/htmltwo中分别建立2个index.html文件:

echo "this is htmlone" > /web/htmlone/index.html

echo "this is htmltwo" > /web/htmltwo/index.html

然后在shell命令行测试nginx虚拟主机:

elinks -dump www.qiguo1.com 显示this is htmlone

elinks -dump www.qiguo2.com 显示this is htmltwo


五.nginx访问控制授权

nginx的访问控制需要通过模块来设定默认提供了2个模块Access和Auth Basic。Access是基于地址来做限制的而Auth Basic是基于http页面来做限制的。

基于Access模块认证的时候官方给出的例子是

location / {
    deny 192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.0.0/16;
    deny all;
}

基于Auth Basic模块认证的时候官方给出的例子是

location / {
    auth_basic"closed site" #表示启动了auth认证auth_name的值为closed site
    auth_basic_user_fileconf/htpasswd #用户认证的文件所在的地方
}

下面测试Auth Basic模块基于http认证的方式

需要首先创建一个密码文件这里需要借助apache提供的htpasswd命令,执行htpasswd后输入密码即可

htpasswd -c -m /etc/nginx/nginx.passwd qiguo

编辑/etc/nginx/nginx.conf文件加入下面代码

location = /test.html {
    root html;
    auth_basic "限制登陆需要账号和密码";
    auth_basic_user_file  /etc/nginx/nginx.passwd;ed
    index  index.html index.htm;
}

重新启动nginx,在浏览器中输入localhost/test.html会弹出让你输入用户和密码的信息证明nginx访问控制授权成功


六.nginx页面索引文件的指定

apache在配置主机的时候可以使用Options Indexes对当访问的目录页面不存在时可以以索引的列表方式显示nginx也提供了同样的功能需要通过Auto_Index模块来实现。实现的方法比较简单官网给出的例子是:

location / {
    autoindex on;
    autoindex_exact_size; #这个选项指定以列表的方式显示的时候精确的匹配文件的大小否则会做文件大小转换
    autoindex_localtime;  #显示的文件的时间是以运行nginx的服务器的时间为标准来显示的
}


七.nginx自定义响应报文

nginx自定义响应报文需要通过Headers这个模块来实现.而且最好添加http协议所支持的响应报文首部。使用的方法很简单官方给出的简单示例如下

add_header Cache_Control private; //自定义Cache_Control的值为private

例如我们可以自己为一个页面自定义一个响应报文配置如下

location = /test.html {
    root html;
    index index.html;
    add_header HTTP_X_FORWARD_FOR 192.168.1.250;
}

保存后重新启动nginx后打开test.html这个文件会看到响应头中多出来了一个HTTP_X_FORWARD_FOR的信息并且其值为192.168.1.250


八.nginx的URL重写功能

nginx的URL重写功能是依靠ngx_http_rewrite_module这个模块来实现的nginx常用的rewrite语法用5个

   set主要是用来设置变量用的,没什么特别的

   ifif主要用来判断一些在rewrite语句中无法直接匹配的条件,比如检测文件存在与否,http header,cookie等

   returnreturn可用来直接设置HTTP返回状态,比如403,404等

   break立即停止rewrite检测

   rewrite设置url重写时最重要的功能其语法使用格式为rewrite 正则 替换 标志位

   rewrite的重写功能和apache基本上是一样但是这里主要说明下rewrite标志位的使用默认的标志位有4个

       break:停止rewrite检测,也就是说当含有break flag的rewrite语句被执行时,该语句就是rewrite的最终结果

       last:停止rewrite检测,但是跟break有本质的不同,last的语句不一定是最终结果

       redirect:返回302临时重定向,一般用于重定向到完整的URL(包含http:部分)

       permanent:返回301永久重定向,一般用于重定向到完整的URL(包含http:部分)


if语句中的判断条件:

正则表达式匹配

   ~ 为区分大小写匹配

   ~* 为不区分大小写匹配

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


文件及目录匹配匹配

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

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

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

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


nginx常用的全局变量

   $args

   $content_length

   $content_type

   $document_root

   $document_uri

   $host

   $http_user_agent

   $http_cookie

   $limit_rate

   $request_body_file

   $request_method

   $remote_addr

   $remote_port

   $remote_user

   $request_filename

   $request_uri

   $query_string

   $scheme

   $server_protocol

   $server_addr

   $server_name

   $server_port

   $uri


这里给出官方的一些URL重写示例

if ($http_user_agent ~ MSIE) {

   rewrite ^(.*)$ /msie/$1 break;

}

rewrite ^/users/(.*)$ /show?user=$1? last;

rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;


九.nginx的status功能

nginx与apache一样Apache有一个mod_status的模块可以查看服务器的运行状况nginx提供了类似的功能并且是通过http_stub_status_module这个模块来完成的。nginx启动status也比较简单但是前提是在编译的时候要安装http_stub_status_module这个模块。要启动nginx的status模块只需要做下面的简单配置即可

location /status {

   stub_status on;

   access_log off;

}

重新启动nginx,访问localhots/status,可以得到下面的内容

Active connections: 1

server accepts handled requests

2 2 35

Reading: 0 Writing: 1 Waiting: 0


官网介绍如下

active connections -- number of all open connections  #打开的活动连接数

server accepts handled requests -- nginx accepted 16630948 connections, handled 16630948 connections (no one was closed just it was accepted), and handles 31070465 requests (1.8 requests per connection) #服务器已经接受的连接数accepted 16630948表示已经处理过的连接数handled 16630948表示已经处理的连接数handles 31070465表示处理的请求数。在启用了keepalive的情况下连接数一般应该大于请求数

reading -- nginx reads request header #nginx正在读取的请求报文数

writing -- nginx reads request body, processes request, or writes response to a client #nginx正在发送的请求报文数

waiting -- keep-alive connections, actually it is active - (reading + writing) #长连接的活动连接数


十.nginx的压缩功能

nginx的gzio模块可以启动压缩功能在访问量高带宽不大的情况下可以显著提高服务器的性能。gzip是通过with-http_gzip_static_module这个模块来完成工作的。给status模块一样也需要在编译的时候编译http_gzip_static_module这个模块。gzip的常用命令如下:

gzip on; //开启或者关闭gzip模块

gzip_buffers: 4 4k; //设置系统获取几个单位的缓存用于存储gzip的压缩结果数据流.例如4 4k 代表以4k为单位按照原始数据大小以4k为单位的4倍申请内存。4 8k 代表以8k为单位按照原始数据大小以8k为单位的4倍申请内存。如果没有设置默认值是申请跟原始数据相同大小的内存空间去存储gzip压缩结果。

gzip_comp_level4; //gzip压缩比1压缩比最小处理速度最快9 压缩比最大但处理最慢传输快但比较消耗cpu。

gzip_min_length1024; //设置允许压缩的页面最小字节数页面字节数从header头中的Content-Length中进行获取。默认值是0不管页面多大都压缩。建议设置成大于1k的字节数小于1k可能会越压越大。

gzip_proxied off; //Nginx作为反向代理的时候启用开启或者关闭后端服务器返回的结果匹配的前提是后端服务器必须要返回包含"Via"的header头。

默认的取值有off|expired|no-cache|no-store|private|no_last_modified|no_etag|auth|any;具体解释如下

   off - 关闭所有的代理结果数据的压缩

   expired - 启用压缩如果header头中包含"Expires" 头信息

   no-cache - 启用压缩如果header头中包含"Cache-Control:no-cache" 头信息

   no-store - 启用压缩如果header头中包含"Cache-Control:no-store" 头信息

   private - 启用压缩如果header头中包含"Cache-Control:private" 头信息

   no_last_modified - 启用压缩,如果header头中不包含"Last-Modified" 头信息

   no_etag - 启用压缩,如果header头中不包含"ETag" 头信息

   auth - 启用压缩, 如果header头中包含"Authorization" 头信息

   any - 无条件启用压缩

   gzip_types匹配MIME类型进行压缩无论是否指定"text/html"类型总是会被压缩的。

下面是常规的gzip配置压缩

http{

   include conf/mime.types;

   gzip on;

   gzip_min_length 1000;

   gzip_buffers 4 8k;

   gzip_http_version 1.1;

   gzip_types text/plain application/x-javascript text/css text/html application/xml;

}

这里借鉴地址http://wenku.baidu.com/link?url=6hkmzQjgGsNqYsHSaa9MceJQ_JPjtSLpBKowi2XnRHvjGRMWzJbBIIEhMSGIx2NGTChFkDhBo6YHonOn2hGbXy0XrgtDuVK5HvP_Uq5EXq3


十一.nginx的SSL功能

nginx要支持SSL功能需要编译的时候指定--with-http_ssl_module选项。nginx的SSL功能就是依靠ngx_http_ssl_module来完成的。要完成对SSL的支持需要生成证书这里我们使用linux默认的CA来生成自签证书并且为我们的nginx颁发一个证书。CA证书的生成这里不再说明这里以本台服务器为例来生成证书。这里不再演示CA的基本配置情况只是给出简单的生成证书的过程。

进入/etc/pki/CA目录下创建3个文件certs crl newcerts3个目录创建index.txt serial 2个文件往serial文件中写入01

openssl genrsa -out private/cakey.pem 1024

openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 3650

然后创建自己的信息注意这里的信息要和等下给我们nginx服务器颁发证书的时候的信息一样输入完成以后就可以为nginx颁发证书。

进入/etc/nginx目录后

openssl genrsa -out nginx.key 1024

openssl req -new -key nginx.key -out nginx.csr -days 3650  输入后填写信息

openssl ca -in nginx.csr -out nginx.crt

输入全部完成以后我们的证书就已经生成完毕nginx.crt这个文件就是我们的证书文件颁证机构就为我们的CA即前面的cacert.pem。下面开始配置nginx让其支持https:

server {

   listen       443;

   server_name  localhost;

   

   ssl                  on;

   ssl_certificate      /etc/nginx/nginx.crt;

   ssl_certificate_key  /etc/nginx/nginx.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;

   }

}

配置完成以后在浏览器中输入https://127.0.0.1中可以看到https协议已经可以使用了但是需要认证因为我们的当前客户端上没有安装我们自己CA服务器的证书。只需要把cacert.pem服务器到一台客户端的机器改成以crt的后缀安装我们的https协议就可以正常使用了。



nginx详细配置教程,布布扣,bubuko.com

nginx详细配置教程

标签:nginx 服务器 linux

原文地址:http://cqgphper.blog.51cto.com/7680112/1412649

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!