gfdxy3322 发表于 2018-10-20 13:38:49

配置Ngnix作为Web Server详解

  IO复用
  http://nginx.org/
  Http服务器
  反向代理 reverse proxy
  mail
  http
  C10k
  单进程;阻塞
  多进程;每个进程响0应一个请求
  进程量大,进程切换次数过多
  每个进程的地址空间是独立,很多空间是重复的数据,所以内存使用效率较低
  线程:thread,
  Light Weight Process, LWP
  每个线程响应一个请求
  线程仍然切换:属于轻量级
  同一个 进程的线程可以共享进程的诸多资源,比如打开的文件
  对内存的需求较之进程略有下降
  快速切换时候会带来线程抖动
  多进程多线程
  多线程:N个请求
  一个线程响应多个请求
  多路IO,IO复用;
  blocking I/O 阻塞I/O
  nonblocking I/o 非阻塞I/O
  I/O multiplexing I/O复用
  signal driven I/O信号驱动的I/O
  asynchronous I/O 异步I/O
  nginx优势:
  支持A I/O
  支持内存映射 mmap
  支持事件驱动event-driven
  httpd:
  MPM
  prefork:一个进程响应一个请求,最多并发1024个
  worker:一个线程显影一个请求,多进程,一个进程生成多个线程
  event:基于事件驱动
  keepalived+ningx:实现高可用
  corosync+ningx
  nginx:
  web服务器
  反向代理
  web
  mail
  Tengine
  varnish,squid
  nginx:cache(disk)
  httpd:cache(disk,memory)
  memcached
  ningx热部署:平滑升级
  主进程主要完成一下工作
  1.读取并验证配置信息
  2.创建,绑定及关闭套接字
  3.启动,终止及维护worker进程的个数
  4.无需终止服务而重新配置工作特性
  5.控制非中断式程序升级,启用新的二进制程序并在需要时回滚至老版本;
  6.重新打开日志文件,实现日志滚动
  7.编译嵌入式perl脚本
  worker进程主要完成任务包括
  1.接收,传入并处理来自客户端的连接
  2.提供反向代理及过滤功能
  3.nginx任何能完成的其他任务
  cache loader进程主要完成任务包括
  1.检查缓存存储中的缓存对象
  2.使用缓存元数据建立内存数据库
  cache manager进程的主要任务
  1.缓存的失效及过期检查
  Nginx的配置有着几个不同的上下文:main, http, server, upstream和location(还有实现邮件服务反响代理的mail)。
  配置语法的格式和定义方式遵循所谓的c风格,因此支持嵌套,还有着逻辑清晰并易于创建,阅读和维护等优势
  支持事件驱动的I/O框架:kqueue    epoll   /dev/poll
  支持sendfile尽可能避免数据拷贝操作(避免数据在用户空间和内存空间来回拷贝)
  # yum info openssl-devel查看openssl-属于哪个组
  # rpm -qi openssl-devel
  # yum groupinfo "Compatibility libraries" 查看某个组的关联包
  yum -y groupinstall'Development tools'
  yum -y groupinstall 'Server Platform Development'
  yum -y groupinstall 'Compatibility libraries' 提供兼容库
  yum -y groupinstall 'Desktop Platform Development'
  1.确认系统时间比软件包时间靠后。
  # date -s 20170213
  Mon Feb 13 00:00:00 EST 2017
  # date -s20:45:50
  # hwclock--set --date="02/13/17 20:48:00"
  # tar -xf nginx-1.10.3.tar.gz
  # du -sh nginx-1.10.3
  6.2Mnginx-1.10.3
  # groupadd-r -g 108 nginx
  # useradd -r -g 108 -u 108 nginx
  # yum -y install gd.i686
  # yum -y install 'pcre-devel'
  # ./configure --help |less
  ./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 \
  --with-file-aio \
  --with-http_image_filter_module
  make && make install
  #########################################################
  启动脚本:
  # vim /etc/rc.d/init.d/nginx
  #!/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
  ;;

  >  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
  ############################################################
  添加执行权限和自启动
  # chkconfig --add nginx
  # chmod +x /etc/rc.d/init.d/nginx
  # chkconfig--list nginx
  nginx          0:off1:off2:off3:off4:off5:off6:off
  # chkconfig nginx on
  # service nginx start
  Starting nginx:                                          
  # ls /var/tmp/nginx/
  clientfcgiproxyscgiuwsgi
  在/usr/html/下存放了测试页,如果不存在可以cp 编译目录下的html的文件直接到/usr/html
  ###############################################################################
  配置文件:
  # cd /etc/nginx/
  # ls
  fastcgi.conf            koi-utf             nginx.conf         uwsgi_params
  fastcgi.conf.default    koi-win             nginx.conf.default   uwsgi_params.default
  fastcgi_params          mime.types          scgi_params          win-utf
  fastcgi_params.defaultmime.types.defaultscgi_params.default
  #.default结尾的都是nginx中默认提供的配置文件
  mime 多用途互联网邮件扩展,主要靠这个识别非文本文档
  fastcgi.conf和fastcgi_params 是用于实现fastcgi功能的,两个文件通常只用一个
  # cp nginx.confnginx.conf.back
  # vim nginx.conf
  worker_processes1; 启动的worker的线程数,通常跟cpu个数相关,
  如果是cpu密集型应用为主,如SSL或压缩应用,则worker数应与CPU数相同;如果负载以IO密集型为主,如响应大量内容给客户,则
  worker数应该为CPU个数的1.5或2倍
  events {
  worker_connections1024;
  }定义事件驱动中每个worker最大的连接数
  http段:
  include       mime.types; 指定所包含的文件
  default_typeapplication/octet-stream; 指定默认支持的类型
  sendfile      on; 定义是否开机sendfile(开启以后会尽量避免数据在用户空间和内核空间来回复制)
  #tcp_nopush   on; 是否推送
  Nagle算法:如果发送端发送多次少量字符的数据包,则第一次发送出去以后 剩下的 先缓存下来而不立即发送
  ,直到接收端发送对前一个数据报文的ACK确认,或者当前字符数据紧急数据,或者积攒到了一定量的数据后再向外发送
  TCP中Nagle算法默认是启用的,但它并不是适合任何场景,对telnet,rlogin这样的远程登录比较合适,但是在某些应用场景下又需要关
  闭它,因为会导致客户端运行很慢,降低了实时响应速度
  keepalive_timeout65; 使用长连接,并指定超时时间
  #gzipon; 对响应给用户的数据是否先压缩
  server段:
  每一个server{}定义一个虚拟主机
  server {
  listen       80; 监听端口
  server_namelocalhost; 基于名称的虚拟主机,IP不同就是基于IP的虚拟主机
  location / {            基于URI路劲来定义访问路径
  root   html;相对路径定义root在/usr/html下
  indexindex.html index.htm;定义index在/usr/html/index.html 或者/usr/html/index.htm
  deny    192.168.1.1; 拒绝某个地址访问
  }
  error_page   500 502 503 504/50x.html; 定义如果返回的错误代码是404则返回的主页是usr/html/50x.html;
  #####################################################################
  location URI {} 表示花括号中所定义的属性对这个URI所有文件都生效,优先级最低
  location = URI {}精确匹配只对当前路径生效 ,优先级最高
  ~   #表示此处URI可以使用正则表达式,区分大小写, 优先级第三
  ~*    #表示此处URI可以使用正则表达式,不区分大小写,优先级第三
  ^~    #表示不使用正则表达式,优先级第二
  ##############################
  定义访问控制,把规则小的放在最前面,默认是允许访问的
  location /{
  deny    192.168.1.1;拒绝某个地址访问
  allow   192.168.1.0/24;允许某个网段
  allow   10.1.1.0/16;
  allow   2620:100:e000::8001;
  deny    all;拒绝所有
  }
  ##########################################################################
  利用auth_basic实现http认证
  location /{
  auth_basic      "Restricted";   指定认证信息
  auth_basic_user_file htpasswd; 指定认证文件路径和文件名
  }
  # yum -y install 安装httpd为了使用htpasswd工具
  # chkconfig --list httpd 确认是关闭的
  # htpasswd -c -m /etc/nginx/.users tom   第一次使用需要-c创建文件,-m指定md5加密方式
  New password:
  Re-type new password:
  Adding password for user tom
  #
  location / {
  root   html;
  indexindex.html index.htm;
  auth_basic   "Restricted Area...";
  auth_basic_user_file   /etc/nginx/.users;
  }
  service nginx restart
  ###########################################################################
  autoindex on:在没有主页的情况下把所有文件都列出来
  autoindex_exac_size on|off 显示每一个文件大小的精确值
  autoindex_localtime 显示当前操作系统的本地时间
  location / {
  root   html;
  indexindex.html index.htm;
  auth_basic   "Restricted Area...";
  auth_basic_user_file   /etc/nginx/.users;
  autoindex on;
  }
  ####################################################################
  stub_status on; 定义状态页面
  location /status {
  stub_status on;
  access_logoff;
  allow ...
  deny all;
  }
  192.168.1.10/status
  Active connections: 3当前的活动连接数
  server accepts handled requests
  3 3 3   已经接受的连接数,已经处理过的连接数,已经处理过的请求数
  Reading: 0 Writing: 1 Waiting: 2
  Reading: 正在读取其首部的请求的个数
  Writing: 正在读取其主体的请求个数,正在处理着其请求内容的个数或者正在向客户端发送响应的个数;
  Waiting: 长连接模式的保持的连接个数
  ###################################################################
  SSL:                      :.,$ s/^\([[:space:]]*\)#/\1/g
  server {
  listen       443 ssl;
  server_namelocalhost;
  ssl_certificate      /etc/nginx/ssl/nginx.crt;   证书
  ssl_certificate_key/etc/nginx/ssl/nginx.key;    私钥
  ssl_session_cache    shared:SSL:1m;
  ssl_session_timeout5m;    会话超时时间
  ssl_ciphersHIGH:!aNULL:!MD5; 加密算法
  ssl_prefer_server_cipherson; 是否允许服务端选择倾向的加密算法
  location / {      定义对应的网页文件在什么路径下
  root   /web/ssl;
  indexindex.html index.htm;
  }
  }
  搭建CA:
  # vim /etc/pki/tls/openssl.cnf
  dir             = /etc/pki/CA
  # cd /etc/pki/CA/
  # ls
  certscrlnewcertsprivate
  # ls private/
  # (umask 077;openssl genrsa 2048 >private/cakey.pem)
  # opensslreq -new -x509 -keyprivate/cakey.pem-out cacert.pem
  # touch serial
  # echo 01 >serial
  # touch index.txt
  # cd /etc/nginx/
  # mkdir ssl && cd ssl
  # (uamsk 077;openssl genrsa 1024 >nginx.key)
  # openssl req -new -key nginx.key-out nginx.csr
  # openssl ca -in nginx.csr-out nginx.crt -days 3650
  # service nginx restart
  https://192.168.1.10/
  ###################################################################
  :set nohlsearch
  定义基于主机名的虚拟主机:
  server {
  listen       80;
  server_namewww.mylinux.com;
  --------------------------------------------
  server {
  listen      80;
  server_name      www.mylinux2.com;
  location / {
  root      /web/www;
  indextesttest.htm;
  }
  }
  # another virtual host using mix of IP-, name-, and port-based configuration
  ---------------------------------------------------------
  nginx -t测试配置文件语法
  #########################################
  实现lnmp(lemp)
  MySQL+PHP
  fastCGI:
  php-fpm:
  127.0.0.1:9000
  编译:php
  mysql:
  # useradd -r mysql
  # mkdir /mydata/data -pv
  mkdir: created directory `/mydata'
  mkdir: created directory `/mydata/data'
  # chown -R mysql.mysql /mydata/data
  # tar -xf mysql-5.5.28-linux2.6-x86_64.tar.gz
  # ln -sv mysql-5.5.28-linux2.6-x86_64 mysql
  # chown -R mysql.mysql mysql/*
  # chmod -R 750 mysql/*
  # fdisk /dev/sdb
  8e
  # partprobe /dev/sdb
  # pvcreate /dev/sdb1
  # vgcreate myvg /dev/sdb1
  # lvcreate -n mydata -L 10G myvg
  # vim /etc/fstab
  /dev/myvg/mydata      /mydata               ext3    defaults      0 0
  # chmod o-rx /mydata/data
  # scripts/mysql_install_db   --user=mysql   --datadir=/mydata/data
  # chown -R root /usr/local/mysql/*
  # cp support-files/mysql.server   /etc/init.d/mysqld
  # chkconfig --add mysqld
  # cp my-large.cnf   /etc/my.cnf
  #vim/etc/my.cnf
  datadir = /mydata/data
  innodb_file_per_table = ON
  log-bin = master-bin
  # service mysqld start
  # vim /etc/profile.d/mysql.sh
  export PATH=$PATH:/usr/local/mysql/bin
  # vim /etc/man.config
  MANPATH /usr/man
  MANPATH /usr/share/man
  MANPATH /usr/local/man
  MANPATH /usr/local/share/man
  MANPATH /usr/X11R6/man
  MANPATH /usr/local/mysql/man 新增一条
  # vim /etc/ld.so.conf.d/mysql.conf
  /usr/local/mysql/lib
  # ldconfig -v 让系统重新读取
  # ls -l /etc/ld.so.cache 缓存到这个文件
  -rw-r--r--. 1 root root 41662 Jul 27 17:15 /etc/ld.so.cache
  # ln -sv /usr/local/mysql/include/usr/include/mysql
  php:
  # yum -y install bzip2-devel
  # yum -y install libcurl-devel
  # tar -xf php-5.4.13.tar.gz
  # ./configure --prefix=/usr/local/php --with-mysql=/usr/local/mysql --with-openssl --enable-fpm --enable-sockets --enable-sysvshm--with-mysqli=/usr/local/mysql/bin/mysql_config --enable-mbstring --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib-dir --with-libxml-dir=/usr --enable-xml    --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2 --with-curl
  # make && make install
  为php提供配置文件:
  # cp php.ini-production/etc/php.ini
  为php-fpm提供Sysv init脚本,并将其添加至服务列表:
  # cd /usr/local/php/etc/
  # ls
  pear.confphp-fpm.conf.default
  # cp php-fpm.conf.defaultphp-fpm.conf
  # vim php-fpm.conf
  pm.max_children = 150 最多多少个
  pm.start_servers = 8 启动的时候启动几个
  pm.min_spare_servers = 5 最少空闲为几个
  pm.max_spare_servers = 10 最多空闲为几个
  # cp sapi/fpm/init.d.php-fpm/etc/init.d/php-fpm
  # chmod +x /etc/init.d/php-fpm
  # chkconfig--add php
  # chkconfig--add php-fpm
  # chkconfig php-fpm on
  # service php-fpm start
  Starting php-fpmdone
  # netstat -tnlp
  tcp      0      0 127.0.0.1:9000            0.0.0.0:*                   LISTEN      113123/php-fpm
  # ps aux |grep php
  php启动了8个子进程
  整合nginx和php5
  # vim /etc/nginx/nginx.conf
  启用:
  location ~ \.php$ {
  root         /web/www;
  fastcgi_pass   127.0.0.1:9000;#所有对.php页面的访问都以fastcgi的方式代理给127.0.0.1:9000这个主机处理
  fastcgi_indexindex.php;       #fastcgi的主页为index.php
  fastcgi_paramSCRIPT_FILENAME/scripts$fastcgi_script_name;
  include      fastcgi_params;
  }
  # vim /etc/nginx/fastcgi_params
  fastcgi_paramGATEWAY_INTERFACECGI/1.1;      #CGI接口
  fastcgi_paramSERVER_SOFTWARE    nginx;      #服务器端软件程序
  fastcgi_paramQUERY_STRING       $query_string;   #查询方式
  fastcgi_paramREQUEST_METHOD   $request_method;#请求方法
  fastcgi_paramCONTENT_TYPE       $content_type;    #内容类型
  fastcgi_paramCONTENT_LENGTH   $content_length;#内容长度
  fastcgi_paramSCRIPT_FILENAME    $document_root$fastcgi_script_name;#用户请求的网页页面文件
  fastcgi_paramSCRIPT_NAME      $fastcgi_script_name;#脚本名称
  fastcgi_paramREQUEST_URI      $request_uri;#启动的是哪个URI
  fastcgi_paramDOCUMENT_URI       $document_uri; #网页路劲URI
  fastcgi_paramDOCUMENT_ROOT      $document_root;
  fastcgi_paramSERVER_PROTOCOL    $server_protocol;#协议版本
  fastcgi_paramREMOTE_ADDR      $remote_addr;    #客户端地址
  fastcgi_paramREMOTE_PORT      $remote_port;    #客户端端口
  fastcgi_paramSERVER_ADDR      $server_addr;   #服务器IP
  fastcgi_paramSERVER_PORT      $server_port;   #服务器端口
  fastcgi_paramSERVER_NAME      $server_name;#服务器名字
  # nginx -t

  # service nginx>  测试是否已经支持php
  # vim index.php
  
  ~
  并在所支持的主页面格式中添加php格式的主页,类似如下:
  location / {
  root   html;
  indexindex.php index.html index.htm;
  }
  而后重新载入nginx的配置文件:

  # service nginx>  、安装xcache,为php加速:
  1、安装
  # tar xf xcache-2.0.0.tar.gz
  # cd xcache-2.0.0
  # /usr/local/php/bin/phpize
  # ./configure --enable-xcache --with-php-config=/usr/local/php/bin/php-config
  # make && make install
  安装结束时,会出现类似如下行:
  Installing shared extensions:   /usr/local/php/lib/php/extensions/no-debug-zts-20100525/
  2、编辑php.ini,整合php和xcache:
  首先将xcache提供的样例配置导入php.ini
  # mkdir /etc/php.d
  # cp xcache.ini /etc/php.d
  说明:xcache.ini文件在xcache的源码目录中。
  接下来编辑/etc/php.d/xcache.ini,找到zend_extension开头的行,修改为如下行:
  zend_extension = /usr/local/php/lib/php/extensions/no-debug-zts-20100525/xcache.so
  注意:如果php.ini文件中有多条zend_extension指令行,要确保此新增的行排在第一位。
  3、重新启动php-fpm
  # service php-fpm restart
  六、补充说明
  如果要在SSL中使用php,需要在php的location中添加此选项:
  fastcgi_param HTTPS on;

页: [1]
查看完整版本: 配置Ngnix作为Web Server详解