nginx常见应用技术

一、Nginx  基础知识

    1、简介
        Nginx ("engine x") 是一个高性能的HTTP和反向代理 服务器,也是一个IMAP/POP3/SMTP代理服务器。Nginx 是由  Igor  Sysoev 为俄罗斯访问量第二的Rambler.ru站点开发的,它已经在该站点运行超过三年时间。
        Nginx是以类BSD许可证的形式发布的。在国内,已经有新浪博客、新浪播客、网易新闻、56.com、Discuz官方论坛、水木社区、豆瓣、迅雷在线等多家网站使用Nginx作为WEB服务器或反向代理服务器。
        图下是Netcraft公司统计的从1995年8月至2014年12月各web服务器的市场占有率曲线图:

    2、 Nginx的优点
        nginx做为HTTP服务器,有以下几项基本特性:
            1)   处理静态文件,索引文件以及自动索引;打开文件描述符缓冲.
            2)   无缓存的反向代理加速,简单的负载均衡和容错.
            3)   FastCGI,简单的负载均衡和容错.
            4)   模块化的结构。包括gzipping,byteranges,chunkedresponses,   以及 SSI-filter等filter。如果由FastCGI或其它代理服务器处理单页中存在的多个SSI,则这项处理可以并行运行,而不需要相互等待。
            5)   支持SSL 和 TLS SNI.

            Nginx专为性能优化而开发,性能是其最重要的考量, 实现上非常注重效率 。它支持内核Poll模型,能经受高负载的考验, 官方测试Nginx能够支撑5W并发连接,在实际生产环境中可支撑2~4W并发连接数。
            Nginx具有很高的稳定性。其它HTTP服务器,当遇到访问的峰值,或者有人恶意发起慢速连接时,也很可能会导致服务器物理内存耗尽频繁交换,失去响应,只能重启服务器。例如当前apache一旦上到200个以上进程,web响应速度就明显非常缓慢了。而Nginx采取了分阶段资源分配技术,使得它的CPU与内存占用率非常低。nginx官方表示保持10,000个没有活动的连接,它只占2.5M内存,所以类似DOS这样的攻击对nginx来说基本上是毫无用处的。就稳定性而言,  nginx比lighthttpd更胜一筹。
            Nginx支持热部署。它的启动特别容易, 并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够在不间断服务的情况下,对软件版本进行进行升级。
            Nginx采用master-slave模型,  能够充分利用SMP的优势,且能够减少工作进程在磁盘I/O的阻塞延迟。当采用select()/poll()调用时,还可以限制每个进程的连接数。
            Nginx代码质量非常高,代码很规范, 手法成熟, 模块扩展也很容易。特别值得一提的是强大的Upstream与Filter链。Upstream为诸如reverseproxy,  与其他服务器通信模块的编写奠定了很好的基础。而Filter链最酷的部分就是各个filter不必等待前一个filter执行完毕。它可以把前一个filter的输出做为当前filter的输入,这有点像Unix的管线。这意味着,一个模块可以开始压缩从后端服务器发送过来的请求,且可以在模块接收完后端服务器的整个请求之前把压缩流转向客户端。
            Nginx能够选择高效的epoll(Linux 2.6内核)、kqueue(Free BSD)、eventport(Solaris 10)作为网络I/O模型,在高连接连接并发的情况下,它能够支持高达50000个并发连接数的响应,而内存、CPU等系统资源消耗却非常低,运行非常稳定。
            更多请参考官网:http://nginx.org/
            下图是Nginx与Apache、Lighttpd的综合对比,来自《实战Nginx 取代Apache的高性能web服务器》

二、Nginx编译安装及调试

1、编译安装Nginx
环境:CentOS 6.6 X86_64位, 源码包 nginx-1.6.2.tar.gz

编译安装nginx需要事先需要安装开发包组"Development Tools"和 "Development Libraries"。同时,还需要专门安装pcre-devel包:
  1. # yum -y groupinstall "Development Tools" "Development Libraries"
  2. # yum -y install pcre-devel
  3. yum install openssl-devel #要开启SSL模块就必须要装这个包
源码包需要到官网下载 http://nginx.org/en/download.html
Nginx编译:
  1. ntpdate 172.16.0.1 #编译前先校准时间
  2. tar xf nginx-1.6.2.tar.gz #解压
  3. cd nginx-1.6.2
  4. groupadd -r -g 108 nginx #新建nginx组和用户
  5. useradd -r -g 108 -u 108 nginx
  1. 常用编译配置介绍参考
  1. 开始编译安装配置
  2. ./configure \
  3. --prefix=/usr/local/nginx \
  4. --conf-path=/etc/nginx/nginx.conf \
  5. --user=nginx \
  6. --group=nginx \
  7. --error-log-path=/var/log/nginx/error.log \
  8. --http-log-path=/var/log/nginx/access.log \
  9. --pid-path=/var/run/nginx/nginx.pid \
  10. --lock-path=/var/lock/nginx.lock \
  11. --with-http_ssl_module \
  12. --with-http_flv_module \
  13. --with-http_stub_status_module \
  14. --with-http_gzip_static_module \
  15. --http-client-body-temp-path=/var/tmp/nginx/client/ \
  16. --http-proxy-temp-path=/var/tmp/nginx/proxy/ \
  17. --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
  18. --with-file-aio
  19. make && make install
  1. 编译完成后,先检查配置文件是否有问题
  2. /usr/local/nginx/sbin/nginx -t # 检查是否有问题
  3. mkdir -pv /var/tmp/nginx/{client,proxy,fastcgi} # 新建目录
  4. /usr/local/nginx/sbin/nginx -t #再次测试
  5.     nginx: the configuration file /etc/nginx/nginx.conf syntax is ok     nginx: configuration file /etc/nginx/nginx.conf test is successful # 出现这提示就没问题
  6. /usr/local/nginx/sbin/nginx # 启动nginx
  7. [root@null nginx-1.6.2]# ss -tnl | grep 80 # 查看是否启用nginx
  8. LISTEN 0 128 *:80 *:*
  9. /usr/local/nginx/html/ # 网页默认路径在安装目录下的html目录下

输入地址访问,安装完成。

2、为nginx提供SysV init脚本和环境变量
  1. 新建文件/etc/rc.d/init.d/nginx,内容如下:
  2. #!/bin/sh
  3. #
  4. # nginx - this script starts and stops the nginx daemon
  5. #
  6. # chkconfig: - 85 15
  7. # description: Nginx is an HTTP(S) server, HTTP(S) reverse \
  8. # proxy and IMAP/POP3 proxy server
  9. # processname: nginx
  10. # config: /etc/nginx/nginx.conf
  11. # config: /etc/sysconfig/nginx
  12. # pidfile: /var/run/nginx.pid
  13. # Source function library.
  14. . /etc/rc.d/init.d/functions
  15. # Source networking configuration.
  16. . /etc/sysconfig/network
  17. # Check that networking is up.
  18. [ "$NETWORKING" = "no" ] && exit 0
  19. nginx="/usr/local/nginx/sbini/nginx"
  20. prog=$(basename $nginx)
  21. NGINX_CONF_FILE="/etc/nginx/nginx.conf"
  22. [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
  23. lockfile=/var/lock/subsys/nginx
  24. make_dirs() {
  25. # make required directories
  26. user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
  27. options=`$nginx -V 2>&1 | grep 'configure arguments:'`
  28. for opt in $options; do
  29. if [ `echo $opt | grep '.*-temp-path'` ]; then
  30. value=`echo $opt | cut -d "=" -f 2`
  31. if [ ! -d "$value" ]; then
  32. # echo "creating" $value
  33. mkdir -p $value && chown -R $user $value
  34. fi
  35. fi
  36. done
  37. }
  38. start() {
  39. [ -x $nginx ] || exit 5
  40. [ -f $NGINX_CONF_FILE ] || exit 6
  41. make_dirs
  42. echo -n $"Starting $prog: "
  43. daemon $nginx -c $NGINX_CONF_FILE
  44. retval=$?
  45. echo
  46. [ $retval -eq 0 ] && touch $lockfile
  47. return $retval
  48. }
  49. stop() {
  50. echo -n $"Stopping $prog: "
  51. killproc $prog -QUIT
  52. retval=$?
  53. echo
  54. [ $retval -eq 0 ] && rm -f $lockfile
  55. return $retval
  56. }
  57. restart() {
  58. configtest || return $?
  59. stop
  60. sleep 1
  61. start
  62. }
  63. reload() {
  64. configtest || return $?
  65. echo -n $"Reloading $prog: "
  66. killproc $nginx -HUP
  67. RETVAL=$?
  68. echo
  69. }
  70. force_reload() {
  71. restart
  72. }
  73. configtest() {
  74. $nginx -t -c $NGINX_CONF_FILE
  75. }
  76. rh_status() {
  77. status $prog
  78. }
  79. rh_status_q() {
  80. rh_status >/dev/null 2>&1
  81. }
  82. case "$1" in
  83. start)
  84. rh_status_q && exit 0
  85. $1
  86. ;;
  87. stop)
  88. rh_status_q || exit 0
  89. $1
  90. ;;
  91. restart|configtest)
  92. $1
  93. ;;
  94. reload)
  95. rh_status_q || exit 7
  96. $1
  97. ;;
  98. force-reload)
  99. force_reload
  100. ;;
  101. status)
  102. rh_status
  103. ;;
  104. condrestart|try-restart)
  105. rh_status_q || exit 0
  106. ;;
  107. *)
  108. echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
  109. exit 2
  110. esac
  1. chmod +x /etc/rc.d/init.d/nginx # 为nginx添加执行权限
  2. chkconfig --add nginx # 添加到系统服务
  3. service nginx start # 可以启动nginx服务了
  4. 输入命令启动nginx,当然直接启动Nginx服务,这一步可以省略
  5. vim /etc/profile.d/nginx.sh # 在/etc/profile.d/添加环境变量nginx.sh文件
  6. export PATH=/usr/local/nginx/sbin:$PATH # 输入以下内容
  7. . /etc/profile.d/nginx.sh # 重读nginx.sh文件
  1. 附带:常见脚本控制命令
  2. start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest
  3. start:开启
  4. stop:关闭
  5. status:查看是否开启
  6. restart:重启服务
  7. reload:重读配置文件
  1. Nginx启动与停止
  2. Nginx启动:经过以上配置,可以直接输入nginx、/usr/local/nginx/sbin/nginxservice nginx stast三种方法

  3. Nginx停止:
  4. kill -信号类型 '/var/run/nginx/nginx.pid'
  5. 1)从容停止Nginx。
    1. kill - QUIT nginx主进程号
    2. kill - QUIT '/var/run/nginx/nginx.pid'
2)快速停止Nginx
       kill - TERM nginx主进程号
kill - TERM '/var/run/nginx/nginx.pid'
     kill - INT nginx主进程号    
kill - INT '/var/run/nginx/nginx.pid'
3)强行停止所有Nginx进程
     pkill -9 nginx
    或killall nginx
3、Nginx配置文件详解:
    1、为nginx.conf着色
由于vim打开nginx.conf没有着色,所以编辑起来很不方便,使用nginx.vim插件就可以着色了

安装方法:
  1. 下载
  2. nginx.vim 放置于~/.vim/syntax/目录
  3. 配置nginx.vim
  4. 而后在~/.vim/filetype.vim中添加如下行:
  5. au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/conf/* if &ft == '' | setfiletype nginx | endif
  6. 其中“/etc/nginx”为nginx配置文件的目录。
  1. [root@null ~]# mkdir -pv .vim/syntax 新建文件夹
  2. mkdir: created directory `.vim'
  3. mkdir: created directory `.vim/syntax'
  4. [root@null ~]# cd .vim/syntax/
  5. [root@null syntax]# mv ~/nginx.vim .
  6. [root@null syntax]# vim nginx.vim 新建文件
  7. au BufRead,BufNewFile /etc/nginx/*,/usr/local/nginx/conf/* if &ft == '' | setfiletype nginx | endif 插入以下文件
  8. [root@null syntax]# vim /etc/nginx/nginx.conf 现在打开文件就有颜色了
2、nginx配置文件详解
  1. vim /etc/nginx/nginx.conf # 打开配置文件
  2. #user nobody; # 使用的用户和组,编译时已经指定,所以注释掉了
  3. worker_processes 1; # 指定工作衍生的进程数(一般等于CPU的总核数或总核数的两倍,例如两个四核CPU,则总和数为8)
  4. #error_log logs/error.log; # 指定错误日志存放的路径,错误日志级别可选项为:[ debug | info | notice | warn | error | crit]
  5. #error_log logs/error.log notice; # 例1
  6. #error_log logs/error.log info; # 例2
  7. #pid logs/nginx.pid; # 指定pid存放的路径
  8. events {
  9. worker_connections 1024; # 允许的连接数
  10. }
  11. http { # 设定http服务器
  12. include mime.types; # 文件扩展名与文件类型映射表
  13. default_type application/octet-stream; # 默认文件类型
  14. #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  15. # '$status $body_bytes_sent "$http_referer" '
  16. # '"$http_user_agent" "$http_x_forwarded_for"';
  17. #access_log logs/access.log main;
  18. sendfile on; # 开启高效文件传输模式,sendifile指定指定nginx是否调用sendfile函数来输出文件,对于普通段设为On,如果用来进行下载等应用IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
  19. #tcp_nopush on; # 防止网络阻塞

  20. #keepalive_timeout 0;
  21. keepalive_timeout 65; # 长连接超时事件,单位为秒
  22. #gzip on; # 开启gzip压缩输出
  23. server { # 虚拟主机配置
  24. listen 80; # 监听端口
  25. server_name localhost; # 域名可以有多个,用空格隔开
  26. #charset koi8-r;
  27. #access_log logs/host.access.log main; # 设置单个虚拟主机访问日志

  28. location / {
  29. root html; # 网站本地目录
  30. index index.html index.htm; # 指定虚拟主机首页文件
  31. }
  32. #error_page 404 /404.html; # 指定错误404的网页文件
  33. # redirect server error pages to the static page /50x.html # 重定向服务器错误页面为静态页面
  34. #
  35. error_page 500 502 503 504 /50x.html;
  36. location = /50x.html { # 转发的类型
  37. root html; # 转发后的网站根目录
  38. }
  39. # proxy the PHP scripts to Apache listening on 127.0.0.1:80
  40. #
  41. #location ~ \.php$ {
  42. # proxy_pass http://127.0.0.1;
  43. #}
  44. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
  45. #
  46. #location ~ \.php$ {
  47. # root html;
  48. # fastcgi_pass 127.0.0.1:9000;
  49. # fastcgi_index index.php;
  50. # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  51. # include fastcgi_params;
  52. #}
  53. # deny access to .htaccess files, if Apache's document root
  54. # concurs with nginx's one
  55. #
  56. #location ~ /\.ht {
  57. # deny all;
  58. #}
  59. }
  60. # listen 8000;
  61. # listen somename:8080;
  62. # server_name somename alias another.alias;
  63. # location / {
  64. # root html;
  65. # index index.html index.htm;
  66. # }
  67. #}
  68. # HTTPS server # https 服务
  69. #
  70. #server {
  71. # listen 443 ssl; # 端口
  72. # server_name localhost; # 主机名
  73. # ssl_certificate cert.pem; # 证书文件路径
  74. # ssl_certificate_key cert.key; # 密钥文件路径
  75. # ssl_session_cache shared:SSL:1m;
  76. # ssl_session_timeout 5m;
  77. # ssl_ciphers HIGH:!aNULL:!MD5;
  78. # ssl_prefer_server_ciphers on;
  79. # location / {
  80. # root html;
  81. # index index.html index.htm;
  82. # }
  83. #}
  84. }
通过上面的nginx.conf配置文件示例,可以看出,nginx.conf的配置文件结构主要由以下几部分构成
  1. http {
  2. upstream {
  3. ...
  4. }
  5. server {
  6. listen IP:PORT;
  7. # 虚拟主机
  8. location /URL {
  9. if ...{
  10. ...
  11. }
  12. root "/path/to/somewhere";
  13. ...
  14. }
  15. }
  16. server {
  17. ...
  18. }
  19. }
  1. 配置文件分类:
  2. main配置段 主配置段
  3. http {
  4. } http相关配置段
  5. 配置指令要以分号结尾,语法格式:
  6. directive value1 [value2...];
  7. 支持使用变量:
  8. 模块内置变量
  9. 自定义变量
  10. set var_name value
  11. 主配置段的指令的类别:
  12. 用于调试、定位问题
  13. 正常运行必备的配置
  14. 优化性能的配置
  15. 事件相关的配置
  16. 正常运行的必备配置:
  17. 1user USERNAME [GROUPNAME];
  18. 指定运行worker进程的用户 和组,例如:
  19. user nginx nginx;s
  20. 2pid /path/to/pid_file
  21. 指定nginxpid文件;
  22. 3worker_rlimit_nofile #;
  23. 指定一个worker进程所能够打开的最大文件句柄数;
  24. 4worker_rlimit_sigpending #;
  25. 指定每个用户能够发往worker的信号的数量;
  26. 优化性能相关的配置:
  27. 1worker_processes #:
  28. worker线程的个数;通常应该为物理CPU核心个数减1
  29. 2worker_cpu_affinity cpumask ...;
  30. 绑定worker进程至指定的CPU上;
  31. CPUMASK
  32. 0001
  33. 0010
  34. 0100
  35. 1000
  36. 例如:
  37. worker_cpu_affinity 00000001 00000010 00000100;
  38. 3timer_resolution t;
  39. gettimeofday();
  40. 4worker_priority nice;
  41. -20, 19
  42. 事件相关的配置:
  43. 1accept_mutex [on|off]
  44. 内部调用用户 请求至各worker时用的负载均衡锁;打开时表示能让多个worker轮流地、序列化地与响应新请求;
  45. 2lock_file /path/to/lock_file;
  46. 3accept_mutex_delay #ms;
  47. 4use [epoll|rgsig|select|poll];
  48. 定义使用的事件模型;建议让Nginx自动选择;
  49. 5worker_connections #;
  50. 每个worker进程所能够响应的最大并发请求数;
  51. 用于调试、定位问题:
  52. 1daemon [off|on]
  53. 是否以守护进程方式启动nginx
  54. 2master_process on|off;
  55. 是否以master/worker模型来运行nginx;
  56. 3error_log /path/to/error_log level;
  57. 错误日志文件及其级别;出于调试的目的,可以使用debug级别,但此级别只有在编译nginx时使用了--with-debug选项才有效;
3、虚拟主机
简介:虚拟主机使用的是特殊的软硬件技术,它把一台运行在因特网上的服务器主机分为一台台“虚拟”的主机,每台虚拟主机都可以是一个独立的网站,可以具有独立的域名,具有完整的internet服务器功能,同一台主机上的虚拟主机之间是完全独立的。从网站访问者来看,每一台虚拟主机和一台独立的主机完全一样。
    利用虚拟主机,不用为每个要运行的网站提供一台单独的Nginx服务器或单独运行一组Nginx进程。虚拟主机提供了在同一台服务器、同一组Nginx进程上运行多个网站的功能。
在Nginx配置文件(nginx.conf)中,一个最简化的虚拟主机配置代码如下
  1. http
  2. {
  3. server
  4. {
  5. listen 80 default;
  6. server_name _*;
  7. access_log logs/default.access.log combined;
  8. location / {
  9. index index.html;
  10. root /data0/htdocs/htdocs;
  11. }
  12. }
  13. }







            




附件列表

     

    posted @ 2014-12-28 23:04  此时  阅读(312)  评论(0编辑  收藏  举报