Nginx学习笔记

一、Nginx简介

        Nginx ("engine x") 是一个高性能且轻量级的 HTTP 和 反向代理 服务器,同时也是一个 IMAP/POP3/SMTP 服务器其特点是占有内存少,并发能力强。我国使用nginx网站用户有:百度、新浪、网易、腾讯等。


二、详解Nginx主配置文件(nginx.conf)

user nobody nobody;#运行用户与组
worker_processes 6;#启动进程,通常设置与CPU数相同
worder_cpu_affinity4; #明确指定使用哪些CPU 如使用1、3核心: 1000 0010
worker_rlimit_nofile51200; #设置最大系统连接数
worker_priority 1; #指定调用CPU优先级;取值范围(-20~20)
#error_loglogs/error.log;
#error_loglogs/error.log notice; #错误日志及日志级别;日志级别有:(debug|info|notice|warn|error|crit|alert|emerg)
#error_loglogs/error.log info;
#pidlogs/nginx.pid; #PID文件路径
lock_filelogs/nginx.lock; #锁文件路径
events { #事件模块
use epoll; #指定事件驱动模型;(kqueue|rtsig|epoll|select|poll|eventport)
worker_connections51200; #定义连接数限制;当超过1024时,须使用"ulimit -n"来解除系统连接限制
}
http { #设置HTTP服务器模块
include mime.types;#设置MIME类型
default_typeapplication/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_loglogs/access.log main; #设置访问日志及日志格式
sendfile on; #指定Nginx是否调用sedfile函数
#autoindex on; #开启索引功能,适合下载服务器,默认关闭
#tcp_nopush on; #防止网络阻塞
#tcp_nodelay on; #防止网络阻塞
#keepalive_timeout0;
keepalive_timeout65; #连接超时时间,单位秒
server_names_hash_bucket_size128; #服务器名字Hash表大小
large_client_header_buffers4 32k; #设定请求缓存大小
client_header_buffer_size2k; #客户端请求头部缓冲区大小
client_body_buffer_size512k; #客户端请求主休缓冲区大小
client_header_timeout60; #客户端请求头部超时时间
client_max_body_size8M; #设置通过Nginx上传的文件大小
proxy_connect_timeout20; #代理连接超时时间
proxy_send_timeout60; #代理发送超时时间
proxy_read_timeout20; #代理接收超时时间
proxy_buffer_size16k; #代理服务器保存用户头信息的缓冲区大小
proxy_buffers 464k; #存放后台服务器缓冲区数量与大小
proxy_busy_buffers_size128k; #高负荷下缓冲大小
proxy_temp_file_write_size128k; #设置缓存文件夹大小
proxy_temp_path/usr/cache_one; #设置缓存文件夹位置
######指定缓冲区的路径、存储方式及大小
proxy_cache_path/usr/proxy_cache_path levels=1:2 keys_zone=cache_one:200m inactive=1dmax_size=30g;
gzip on; #开启Gzip压缩功能
gzip_min_length 1k;#最小压缩文件大小
gzip_buffers 4 16k;#压缩缓存区
gzip_http_version1.1; #压缩版本
gzip_proxied off; #在代理中是否启用压缩功能
gzip_comp_level 5;#压缩级别;默认为1,取值范围(1-9)
######压缩文件类型
gzip_typestext/plain application/x-javascript text/css application/xmlapplication/javascript;
gzip_vary on;
upstream allen { #定义负载均衡配置,必须定义在"server"之外
ip_hash; #基于客户端IP地址完成请求的分发,可以实现同一个客户端的请求发送到同一台服务器;有三种调度算法:轮询(round-robin)、ip哈希(ip_hash)和最少连接(least_conn)
server 172.16.14.2weight=1;#定义一个后端服务器;weight:权重 max_fails:最大失败连接次数,失败连接超时时间由fail_timeout设置 fail_timeout:等待请求目标服务器发送响应时长 backup:所有服务器都故障时才启用此服务器 down:手动记录此服务器不在做任何处理请求
server 172.16.14.3weight=1;
}
server { #定义一个虚拟主机,可以定义多个
listen 80; #监听端口
server_namewww.allen.com; #定义主机名称
#charset koi8-r; #设置字符集
#access_loglogs/host.access.log main;
location / { #可以定义多个,也可以嵌套
root /web; #设置网站文件存放目录
index index.phpindex.html index.htm; #设置默认访问主页
}
location /status {
stub_status on; #开启Nginx状态监测
access_log off; #关闭日志访问
}
location ~ \.php$ {#定义以".php"结尾的文件
root /web; #定义php服务器网站存放目录
fastcgi_pass172.16.14.2:9000; #定义fastcgi服务器地址及端口
fastcgi_indexindex.php; #定义默认访问主页
fastcgi_paramSCRIPT_FILENAME /scripts$fastcgi_script_name;
includefastcgi_params; #定义fastcgi访问文件
}
#location ~.*\.(gif|jep|jpeg|png|bmp|swf|js|css|js|)$ {
# proxy_cachecache_one; #设置缓存区
# proxy_cache_valid200 304 12h; #设置缓存时间
# proxy_cache_valid301 302 1m;
# proxy_cache_validany 1m;
# proxy_set_headerHost $host; #设置发送到代理服务器请求头部添加额外信息
# proxy_set_headerX-Real-IP $remote_addr;
# proxy_set_headerX-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_passhttp://allen;
#}
#location / {
# if($request_method == “PUT”) { #如果客户请求动作为"PUT"就转到定义的地址
# proxy_passhttp://www.allen.com:8080;
# }
# if ($request_uri~ "\.(jpg|gif|jpeg|png)$") { #如果客户端请求"uri"有已经定义的文件结尾的文件就转到定义好的地址然后跳出
# proxy_passhttp://p_w_picpathservers;
# break;
# }
#if($http_user_agent ~ MSIE) { #如果客户端请求使用的浏览器是IE,不管请求地址是什么都转到"/msie/"下面并跳出
#rewrite ^(.*)$/msie/$1 break;
注释:
·last - 完成重写指令,之后搜索相应的URI或location。
·break - 完成重写指令。
·redirect - 返回302临时重定向,如果替换字段用http://开头则被使用。
·permanent - 返回301永久重定向
#}
#}
#error_page 404 /404.html;
# redirect servererror pages to the static page /50x.html
#
error_page 500 502503 504 /50x.html; #定义错误返回页面
location =/50x.html {
root html;
}
# proxy the PHPscripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php${
# proxy_pass http://127.0.0.1;#定义以".php"结尾的全部转到指定的地址
#}
# pass the PHPscripts to FastCGI server listening on 127.0.0.1:9000
#
# deny access to.htaccess files, if Apache's document root
# concurs withnginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual hostusing mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listensomename:8080;
# server_namesomename alias another.alias;
# location / {
# root html;
# index index.htmlindex.htm;
# }
#}
# HTTPS server
#
#server { #定义一个HTTPS服务器
# listen 443;
# server_namelocalhost;
# ssl on;
# ssl_certificatecert.pem; #私钥文件
#ssl_certificate_key cert.key; #颁发的证书
#ssl_session_timeout 5m; #会话超时时间
# ssl_protocolsSSLv2 SSLv3 TLSv1; #SSL协议版本
# ssl_ciphersHIGH:!aNULL:!MD5;
#ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.htmlindex.htm;
# }
#}
}

三、if语句

语法:if (condition) { ...
}
默认值:none
使用字段:server, location
判断一个条件,如果条件成立,则后面的大括号内的语句将执行,相关配置从上级继承。
可以在判断语句中指定下列值:
·一个变量的名称;不成立的值为:空字符传""或者一些用“0”开始的字符串。
·一个使用=或者!=运算符的比较语句。
·使用符号~*和~模式匹配的正则表达式。

四、URL重写模块(Rewrite)

~为区分大小写的匹配。
~*不区分大小写的匹配(allen匹配Allen)。
!~和!~*意为“不匹配的”。
使用-f和!-f检查一个文件是否存在。
使用-d和!-d检查一个目录是否存在。
使用-e和!-e检查一个文件,目录或者软链接是否存在。
使用-x和!-x检查一个文件是否为可执行文件。
正则表达式的一部分可以用圆括号,方便之后按照顺序用$1-$9来引用。

配置实例:

if ($http_cookie~* "id=([^;] +)(?:;|$)" ) {
set $id $1;
}
if ($request_method= POST ) {
return 405;
}
if (!-f$request_filename) {
break;
proxy_passhttp://127.0.0.1;
}
if ($slow){
limit_rate10k;
}
if ($invalid_referer){
return 403;
}
if ($args^~ post=140){
rewrite^ http://example.com/ permanent;
}


五、Nginx负载均衡配置实例

wKioL1Y5xL_RnDUPAAT76KS3Zds001.jpg

两台WEB服务器就使用"Apahce"来实现,这里使用rpm包安装方式;然后提供一个测试页面

1、编译安装Nginx

安装Nginx依赖环境
[root@nginx~]# yum -y groupinstall "Development tools" "Server PlatformDevelopment"
[root@nginx~]# yum -y install pcre-devel

添加Nginx运行用户
[root@nginx~]# useradd -r nginx
[root@nginx~]# tar xf nginx-1.4.2.tar.gz
[root@nginx~]# cd nginx-1.4.2
编译安装Nginx
[[email protected]]# ./configure \
>  --prefix=/usr \                      #Nginx安装目录
>  --sbin-path=/usr/sbin/nginx \        #nginx执行程序安装路径
>  --conf-path=/etc/nginx/nginx.conf \  #Nginx主配置文件存放路径
>  --error-log-path=/var/log/nginx/error.log \   #日志文件存放路径
>  --http-log-path=/var/log/nginx/access.log \
>  --pid-path=/var/run/nginx/nginx.pid \        #PID文件存放路径
>  --lock-path=/var/lock/nginx.lock\            #锁文件存放路径
>  --user=nginx\                                #指定运行Nginx用户
>  --group=nginx\                               #指定运行Nginx组
>  --with-http_ssl_module\                      #开启SSL加密模块
>  --with-http_flv_module\                      #支持flv流媒体模块
>  --with-http_stub_status_module\              #开启状态检测模块
>  --with-http_gzip_static_module\              #开启gzip静态压缩模块
>  --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/ \       #fcgi缓存目录
>  --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \         #uwsgi缓存目录
>  --http-scgi-temp-path=/var/tmp/nginx/scgi \           #scgi缓存目录
>  --with-pcre                                           #启动正则表达式
[[email protected]]# make && make install

2、为Nginx提供Sysv服务脚本

#!/bin/sh
#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/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

3、将Nginx加入到系统服务并启动

[root@nginx~]# chmod +x /etc/rc.d/init.d/nginx
[root@nginx~]# chkconfig --add nginx
[root@nginx~]# service nginx start
正在启动 nginx:                                           [确定]

4、查看Nginx进程并访问测试

[root@nginx~]# ps aux|grep nginx
root     2557  0.0  0.2  44444   816 ?  Ss  15:20   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx    2558  0.7  0.5  44852  1508 ?  S    15:20   0:00 nginx: worker process

wKiom1Y5xWHwhFi2AAIn-NIQTuE879.jpg

5、在WEB1服务器上安装Httpd并启动

[root@web1~]# yum -y install httpd
[root@web1~]# service httpd start

6、为WEB1服务器提供一个测试页面并做访问测试

[root@web1~]# echo 'web1 172.16.14.2' > /var/www/html/index.html

wKiom1Y5xcexOvnQAAAphOwWDjU643.jpg

7、在WEB2服务器上面安装Httpd并启动

[root@web2~]# yum -y install httpd
[root@web2~]# service httpd start

8、为WEB2服务器提供一个测试页面并做访问测试

[root@web2~]# echo 'web1 172.16.14.3' > /var/www/html/index.html

wKioL1Y5xmDiFLDbAAAxVIEoYeo561.jpg



配置Nginx实现负载均衡

1、修改主配置文件

#user  nobody;
worker_processes  4;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
worker_rlimit_nofile    51200;
#pid        logs/nginx.pid;
events {
    use epoll;
    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;
    server_names_hash_bucket_size 128;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 300m;
    client_body_buffer_size 512k;
    sendfile        on;
    tcp_nopush      on;
    keepalive_timeout  65;
    proxy_connect_timeout   20;
    proxy_send_timeout      60;
    proxy_read_timeout      20;
    proxy_buffer_size       16k;
    proxy_buffers           4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    gzip on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 5;
    gzip_vary on;
    upstream allen {
        server 172.16.14.2;
        server 172.16.14.3;
     }
    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            proxy_pass  http://allen;
            index index.html index.htm;
        }
        # redirect server error pages to thestatic page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

2、测试Nginx主配置文件语法,并重新加载

[root@nginx ~]#nginx -t
nginx: theconfiguration file /etc/nginx/nginx.conf syntax is ok
nginx:configuration file /etc/nginx/nginx.conf test is successful
[root@nginx ~]#service nginx reload

3、访问Nginx主机验证是否实现负载均衡,需要多刷新几次

web1访问成功

wKiom1Y5xwLDdXMPAAAqd7X50vc655.jpg

web2访问成功

wKiom1Y5xyWiGsnJAAAp0CMvrDk069.jpg



Nginx实现后端健康状态检测

1、修改Nginx主配置文件如下

upstream allen {
        server 172.16.14.2      backup;
        server 172.16.14.3      max_fails=3 fail_timeout=2s;
    }
此处要注意:
backup:作为备份服务器,当所有服务器都停止了服务,此时backup备份机会启用
max_fails:请求超时后,最大检测后端服务器次数
fail_timeout:超时时间;默认为10s

2、重新加载配置文件

[root@nginx ~]#service nginx reload

3、测试访问到的页面是否为WEB2服务器的

wKioL1Y5x_qD7hZBAABSlD46i9k377.jpg

4、此时,停止WEB2服务器的Httpd服务,验证请求的内容是否为WEB1服务器内容

[root@web2 ~]#service httpd stop
Stoppinghttpd:                                           [  OK  ]

wKiom1Y5yCOzgZA8AAAuhjxFTBI444.jpg

5、把WEB2服务器Httpd服务启动,此时请求到的内容为WEB2服务器。


Nginx添加第三方模块实现过载保护

1、下载扩展补丁包,解压并打补丁

下载地址:https://codeload.github.com/alibaba/nginx-http-sysguard/zip/master

[root@nginx ~]#unzip nginx-http-sysguard-master.zip
[root@nginx ~]# cdnginx-1.4.2
[[email protected]]# patch -p1 <../nginx-http-sysguard-master/nginx_sysguard_1.3.9.patch

2、重新编译安装Nginx

[[email protected]]# ./configure \
>   --prefix=/usr \
>   --sbin-path=/usr/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/ \
>   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi\
>   --http-scgi-temp-path=/var/tmp/nginx/scgi \
>   --with-pcre \
>  --add-module=/root/nginx-http-sysguard-master/
[[email protected]]# make && make install

3、  修改Nginx配置文件添加过载保护;这里说明下为了测试方便,把CPU负载调的比较低

[email protected]]# cd /etc/nginx/
[root@nginx nginx]#vim nginx.conf
在"server"模块中添加如下内容
    sysguard on;    #开启过载保护功能
    sysguard_load load=0.3action=/loadlimit;    #cpu负载超过0.3就保护,"action"过载保护动作
    #sysguard_mem swapratio=20% action=/swaplimit;#交换分区过载保
    #sysguard_mem free=100Maction=/freelimit;     #内存过载保护
    location /loadlimit {
    return 503;    #系统过载返回503
    }
注意:由于新添加了功能需要重启Nginx服务
[root@nginx nginx]#service nginx restart

4、  安装"htop"工具,监测负载

[root@nginx ~]# yum-y install htop
[root@nginx ~]#htop

5、在另一台主机使用apache自带的压力测试工具ab做压测;在压测前先访问一下是否正常。

[root@web1 ~]# ab-n 50000 -c 1000 http://172.16.14.1/index.html

6、查看Nginx服务器的负载状况

wKioL1Y5zWaARkJ-AAC7M***8vY235.jpg

7、 测试访问Nginx服务器是否能正常访问

wKioL1Y5zZmzg-V3AAIPZHuaZPQ003.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章