初识Nginx及其LNMP搭建

Nginx介绍

nginx
  www服务软件 俄罗斯人开发 开源 性能很高 web产品 大小780k  c语言开发
  本身是一款静态www软件,不能解析php jsp .do

最大特点
  静态小文件(1m),支持高并发,占用资源少 3w并发,10个进程,内存150M(unix、linux、windows都支持)
  crtl -I 域名  返回的http信息可以看到使用的web服务器

其他特点
  1、配置简单、灵活、轻量
  2高并发小文件,静态几万并发
  3、功能种类多,但是每个功能都不是特别强
  4支持epoll模型,使得nginx支持高并发。apache 使用select模型()
    宿舍大妈案例,有朋友来宿舍找你
    select即大妈带你逐一挨个去每个房间找(即线性轮回)
    epoll即大妈找宿舍人员名单,房间号信息,告诉你房间号(回调callback)
    所以大并发连接时select性能就下降
  5、nginx可以配合动态服务(fastcgi接口)
  6、利用nginx可以对ip限速,可以限制连接数
另外
  基于名字端口及ip的多虚拟主机站点
  支持rewrite及正则
  支持基于客户端ip地址和http基本认证的访问控制
  支持http响应速率限制
  支持同一ip地址的并发连接或请求数限制

一般网站并发依赖如下
  nginx  1-3w并发
  php   300-800
  db    300-800

nginx服务从大的方面的功能:
  a、web服务,邮件服务
  b、负载均衡(反向代理)
  c、web cache(web缓存),相当于squid(CDN主要使用)


nginx的应用场合
  1、静态服务(图片,视频)是另一个lighttpd。并发:几万并发html js css flv jpg gif
  2、动态服务  nginx+fastcgi方式运行php,jsp,动态并发500-1500(apache+php lighttpd+fastcgi)
  3、反向代理,负载均衡。日pv2000w以下,并发1w以下都可以直接用nginx做代理 (其他代理haproxy软件,F5 ,A10)
  4、缓存服务,类似squid varnish ats

nginx支持虚拟主机,一个server标签就是一个虚拟机
  1、基于域名的虚拟主机   通过域名来区分虚拟主机    应用于外部网站
  2、基于端口的虚拟主机   通过端口来区分虚拟主机   内部网站  网站后台
  3、基于ip的虚拟主机    几乎不用,不支持ifconfig别名,配置文件可以

2017-05-30
nginx-1.13.1 mainline version has been released.
2017-04-12
nginx-1.12.0 stable version

NGINX安装(1.8.1)

1、安装PCRE (Perl Compatible Regular Expressions)
PCRE 中文perl兼容正则表达式,HTTP rewrite module requires the PCRE library
# yum install pcre  pcre-devel -y

2、安装OPENSSL    SSL modules require the OpenSSL library
# yum install openssl-devel -y

开始安装nginx
a、添加用户
#useradd  nginx -s /sbin/nologin -M

b、配置安装
tar -zxvf nginx-1.8.1.tar.gz
cd nginx-1.8.1
./configure --prefix=/usr/local/nginx-1.8.1 --user=nginx --group=nginx 
--with-http_stub_status_module --with-http_ssl_module
make && make install
ln -s /usr/local/nginx-1.8.1/ /usr/local/nginx

c、启动 #
/usr/local/nginx/sbin/nginx d、查看进程 # ps -ef | grep nginx | grep -v grep root 1713 1 0 23:47 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx nginx 1714 1713 0 23:47 ? 00:00:00 nginx: worker process e、查看nginx编译参数及版本 /usr/local/nginx/sbin/nginx -V nginx version: nginx/1.8.1 built by gcc 4.4.7 20120313 (Red Hat 4.4.7-16) (GCC) built with OpenSSL 1.0.1e-fips 11 Feb 2013 TLS SNI support enabled configure arguments: --prefix=/usr/local/nginx-1.8.1 --user=nginx --group=nginx --with-http_stub_status_module --with-http_ssl_module

配置3个虚拟主机实践

#mkdir -p /usr/local/nginx/html/{bbs,www,blog}    用于放置虚拟主机网页目录    
#echo "www.gtms.org" > /usr/local/nginx/html/www/index.html
#echo "bbs.gtms.org" > /usr/local/nginx/html/bbs/index.html
#echo "blog.gtms.org" > /usr/local/nginx/html/blog/index.html
#mkdir /usr/local/nginx/conf/extra    用于放置虚拟主机配置文件目录

在extra目录先建立站点配置文件 www.conf
/bbs.conf/blog.conf,内容如下 root@node83 extra]# cat www.conf bbs.conf blog.conf #www.conf server { listen 80; server_name www.gtms.org; location / { root html/www; index index.html; } } #bbs.conf server { listen 80; server_name bbs.gtms.org; location / { root html/bbs; index index.html; } } #blog.conf server { listen 80; server_name blog.gtms.org; location / { root html/blog; index index.html; } } #vi /usr/local/nginx/conf/nginx.conf 在http标签段加入以下内容 include extra/www.conf; include extra/bbs.conf; include extra/blog.conf; #/usr/local/nginx/sbin/nginx -t 检查ok后# /usr/local/nginx/sbin/nginx -s reload

从另一台主机配置hosts文件进行测试
[root@node82 nginx]# curl 192.168.0.83  通过ip访问默认走第一个配置的主机
www.gtms.org
[root@node82 nginx]# curl www.gtms.org
www.gtms.org
[root@node82 nginx]# curl bbs.gtms.org
bbs.gtms.org
[root@node82 nginx]# curl blog.gtms.org
blog.gtms.org


配置nginx状态页面(--with-http_stub_status_module)

#vi /usr/local/nginx/conf/nginx.conf
在http标签段加入以下内容
include status/www.conf;

在extra目录先建立站点配置文件 status.conf
#status
server {
        listen       80;
        server_name  status.gtms.org;
        location / {
        stub_status on;
        access_log off;
        }
        }

#/usr/local/nginx/sbin/nginx -t 检查ok后# /usr/local/nginx/sbin/nginx -s reload

从另一台主机配置hosts文件进行测试 
[root@node82 nginx]# curl status.gtms.org  #对后端发起的活动连接数,即正在处理的活动连接数
Active connections: 1 
server accepts handled requests
 7 7 11 
Reading: 0 Writing: 1 Waiting: 0

nginx状态参数
server   nginx启动到现在共处理了 7个连接
accepts  nginx启动到现在共成功创建7次握手,和server相同,说明没丢失请求
handled requests  表示共处理了11次请求
Reading: Nginx 读取到客户端的Header信息数.
Writing: Nginx 返回给客户端的Header信息数.
Waiting: 开启keep-alive的情况下,这个值等于 active – (reading + writing),意思就是Nginx已经处理完成,正在等候下一次请求指令的驻留连接.
所以,在访问效率高,请求很快被处理完毕的情况下,Waiting数比较多是正常的.如果reading +writing数较多,则说明并发访问量非常大,正在处理过程中.



NGINX日志

Nginx错误日志
ngx_core_module模块负责http://nginx.org/en/docs/ngx_core_module.html#error_log Syntax: error_log file [level]; Default: error_log logs/error.log error; Context: main, http, mail, stream, server, location error_log 级别分为 debug, info, notice, warn, error, crit,alert,emerg(不要配置低等级,带来很大磁盘IO,如果日志太多,可以清空再看 Nginx访问日志
ngx_http_log_module模块负责http:
//nginx.org/en/docs/http/ngx_http_log_module.html Syntax:
  access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
  access_log off; 表示不记录访问日志
Default:
  access_log logs/access.log combined;
Context: (一般配置在vhost中)
  http, server, location, if in location, limit_except


Example:
access_log logs/access_www.log main gzip buffer=32k flush=5s;
For gzip compression to work, nginx must be built with the zlib library.
也可以直接发到远程服务器
access_log syslog:server=address[,parameter=value]  [format [if=condition]];


log_format  用来定义记录日志的格式(可以定义多种格式,取不同名字)
access_log 用来指定日志文件的路径及使用的何种日志格式记录
nginx默认注释掉的
#log_format main
'$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' (http_referer从哪过来的) # '"$http_user_agent" "$http_x_forwarded_for"';(反向代理记录客户端ip) #access_log logs/access.log main;


1.$remote_addr 与$http_x_forwarded_for 用以记录客户端的真实ip地址; 2.$remote_user:用来记录客户端用户名称; 3.$time_local : 用来记录访问时间与时区; 4.$request :   用来记录请求的url与http协议; 5.$status :   用来记录请求状态;成功是200, 6.$body_bytes_sent :记录发送给客户端文件主体内容大小; 7.$http_referer :  用来记录从哪个页面链接访问过来的; 8.$http_user_agent :记录客户端浏览器的相关信息;
日志实例:192.168.0.82 - - [15/Dec/2016:02:04:24 +0800] "GET / HTTP/1.1" 200 18 "-" "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2" "-"

Nginx访问日志轮询切割(没有自己的切割工具
简单的日志轮询脚本
vi cut_nginx_log.sh #!/bin/sh Dateformat=`date +%Y%m%d` Basedir="/usr/local/nginx" Nginxlogdir="$Basedir/logs" Logname="access_www" [ -d $Nginxlogdir] && cd $Nginxlogdir || exit 1 [ -f ${Logname}.log ] || exit 1 /bin/mv ${Logname}.log ${Dateformat}_${Logname}.log $Basedir/sbin/nginx -s reload 写入crontab 00 00 * * * /bin/sh /home/script/cut_nginx_log.sh >/dev/null 2>&1 日志分析相关工具: syslog,rsyslog,Awstats,flume,logstash scrash scribe kafka,storm。ELK=Elasticsearch+Logstash+Kibana

Nginx Rewrite(需PCRE支持)

1、指令语法(perl正则)
指令语法rewrite regex replacement [flag]
默认值 none
应用位置 server,location,if

实践:
1、增加rewrite规则
root@node83 extra]# cat /usr/local/nginx/conf/extra/www.conf #www.conf
server {            
        listen  80;
        server_name     black.org;
        rewrite ^/(.*) http://www.gtms.org/$1 permanent;  
        }
server 
{
        listen 80;
        server_name www.gtms.org;
        location / {
                root html/www;
                index index.html index.htm;
                }
}

2、在www目录下创建此文件
[root@node83 www]# cat gtms.html  
rewrite

3、重新加载
root@node83 www]# /usr/local/nginx/sbin/nginx -s reload

4、配置好hosts文件,在浏览器输入black.org/gtms.html
   ==>网址跳转至http://www.gtms.org/gtms.html
   ==>显示gtms.html的内容


flag标记:
  1.last     相当于apache里面的[L]标记,表示rewrite,继续向下匹配新的location URI规则
  2.break   本条规则匹配完成后,终止匹配,不再匹配后面的规则。
  3.redirect    返回302临时重定向,浏览器地址会显示跳转后的URL地址。
  4.permanent   返回301永久重定向, 浏览器地址会显示跳转后的URL地址。


Nginx Rewrite的应用场景,在企业里应用非常广泛(一般开发搞给运维)
  1、可以调整用户浏览的url,看起来更规范
  2、便于搜索引擎及用户体验,动态url转成伪静
  3、旧域名访问跳转到新域名 ,301跳转
  4、根据特殊变量、目录、客户端的信息(安卓?苹果?)进行url跳转

NGINX之动态服务

CGI & FastCGI

CGI  
  Common Gateway Interface通用网关接口,用于HTTP服务与其他服务通信交流的一种工具,必须运行在网络服务器上。
  性能差,每次http遇到动态程序都需要重新启动解释器,之后结果返回http,高并发不可用,安全性也差,因此诞生了FastCGI
FastCGI
  是一个可伸缩的,高速的在http服务器和动态脚本语言间通信的接口(FastCGI在linux下是socket,这个socket可以是文件socket,也可以是ipscoket),主要优点是把动态语言和http服务器分离。 特点:
1、是http服务器和动态脚本语言间通信的接口或者工具 2、优点是把动态解析和http服务器分离开来,使Ninx专一处理静态请求和向后转发动态请求 3、Nginx、Apache、lighted都支持 4、接口方式采用C/S结构,分为客户端(http服务器)和服务器端(动态语言解析服务器) 5、php动态语言服务端可以启动多个FastCGI守护进程(例如php-fpm) 6、http服务器通过FastCGI客户端(例如Nginx fastcgi_pass)和动态语言FastCGI服务端通信(例如 php-fpm)

Nginx FastCGI运行原理

Nginx不支持对外部程序的直接调用或者解析,所有的外部程序(包括PHP)必须通过FastCGI接口来调用。
FastCGI接口在Linux下是socket(这个socket可以是文件socket,也可以是ip socket)。
为了调用CGI程序,还需要一个FastCGI的wrapper(wrapper可以理解为用于启动另一个程序的程序),这个wrapper绑定在某个固定socket上,如端口或者文件socket。
当Nginx将CGI请求发送给这个socket的时候,通过FastCGI接口,wrapper接收到请求,然后派生出一个新的线程,这个线程调用解释器或者外部程序处理脚本并读取返回数据;
接着,wrapper再将返回的数据通过FastCGI接口,沿着固定的socket传递给Nginx;最后,Nginx将返回的数据发送给客户端。这就是Nginx+FastCGI的整个运作过程,如图

php 5.3.27安装(一般由开发选择版本)

php5.3及以上   编译参数--enable-fpm
php5.2            编译参数--enable-fastcgi --enable-fpm --enable-force-cgi
php5.2         参考http://blog.zyan.cc/nginx_php_v6

1、安装lib库
yum install zlib-devel libxml2-devel libjpeg-turbo-devel libiconv-devel -y
yum install freetype-devel libpng-devel gd-devel libcurl-devel libxslt-devel -y
=======================如下包改名了
libjpeg-devel====>libjpeg-turbo-devel-1.2.1-3.el6_5.x86_64
curl-devel   ====>libcurl-devel-7.19.7-40.el6_6.4.x86_64
=======================检查安装情况
#rpm -qa freetype-devel libjpeg-turbo-devel libpng-devel gd-devel libcurl-devel libxslt-devel

libiconv-devel:没有被yum安装,需要需要手动安装 (GNU的libiconv是字符编码转换库。)
mkdir -p /home/tools
cd /home/tools
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.14.tar.gz
tar -zxf libiconv-1.14.tar.gz
cd libiconv-1.14
./configure --prefix=/usr/local/libiconv
make
make install
cd ../
安装libmcrypt-devel mhash mhash-devel mcrypt #wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo (官方libmcrypt-devel的yum源没有) #yum install libmcrypt-devel mhash mhash-devel mcrypt -y libmcrypt库非必需安装,但是可能会用 编译安装php php-5.3.29(附5.6编译参数) tar xf php-5.3.29.tar.gz cd php-5.3.29 ./configure --prefix=/usr/local/php5.3.29 --with-mysql=/usr/local/mysql --with-mysql=mysqlnd这样本地就不需要本地mysql了 --with-iconv-dir=/usr/local/libiconv --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fpm --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --enable-short-tags --enable-zend-multibyte --enable-static --with-xsl --with-fpm-user=nginx --with-fpm-group=nginx --enable-ftp before make:(如果报错,在make之前做) find / -name libmysqlclient.so.18 ln -s /usr/local/mysql/lib/libmysqlclient.so.18 /usr/lib64/ touch ext/phar/phar.phar ==========================
echo
"/usr/local/mysql/lib">>/etc/ld.so.conf ldconfig ========================== #make #make install
查看PHP编译参数
# /usr/local/php/bin/php -i |grep
configure Configure Command =>  './configure'  '--prefix=/usr/local/php5.3.29' '--with-mysql=mysqlnd' '--with-iconv-dir=/usr/local/libiconv'
'--with-freetype-dir' '--with-jpeg-dir' '--with-png-dir' '--with-zlib' '--with-libxml-dir=/usr' '--enable-xml' '--disable-rpath'
'--enable-safe-mode' '--enable-bcmath' '--enable-shmop' '--enable-sysvsem' '--enable-inline-optimization' '--with-curl'
'--with-curlwrappers' '--enable-mbregex' '--enable-fpm' '--enable-mbstring' '--with-mcrypt' '--with-gd' '--enable-gd-native-ttf'
'--with-openssl' '--with-mhash' '--enable-pcntl' '--enable-sockets' '--with-xmlrpc' '--enable-zip' '--enable-soap' '--enable-short-tags'
 '--enable-zend-multibyte' '--enable-static' '--with-xsl' '--with-fpm-user=nginx' '--with-fpm-group=nginx' '--enable-ftp'


#ln
-s /usr/local/php5.3.29/ /usr/local/php #cp /home/tools/php5.3.27/php.ini-production /usr/local/php/lib/php.ini
#cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf #/usr/local/php/sbin/php-fpm
#lsof -i:9000
COMMAND    PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
php-fpm 127111  root    7u  IPv4 113033      0t0  TCP localhost:cslistener (LISTEN)
php-fpm 127112 nginx    0u  IPv4 113033      0t0  TCP localhost:cslistener (LISTEN)
php-fpm 127113 nginx    0u  IPv4 113033      0t0  TCP localhost:cslistener (LISTEN)
#
grep -Ev "^;|^$" /usr/local/php/etc/php-fpm.conf | grep -v "^$" [global] [www] user = nginx group = nginx listen = 127.0.0.1:9000 pm = dynamic pm.max_children = 5 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3 调优参数php-fpm(可以作为生产标准) [global] pid = /app/logs/php-fpm.pid  默认注释(可不改) error_log = /app/logs/php-fpm.log  默认注释(可不改) log_level = error #notice改为error rlimit_files = 32768 #主进程文件描述符 events.mechanism = epoll #使用epoll模型 [www] user = nginx group = nginx listen = 127.0.0.1:9000 listen.owner = nginx listen.group = nginx pm = dynamic pm.max_children = 1024 #可以创建的子进程的数量 pm.start_servers = 16 #初始的子进程个数 pm.min_spare_servers = 5 #空闲时最少子进程数 pm.max_spare_servers = 20 #最大的剩余空间
pm.process_idle_timeout
= 15s; #子进程空闲超时退出时间 pm.max_requests = 2048 #每个子进程的最大请求 slowlog = /app/logs/$pool.log.slow request_slowlog_timeout = 10 php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f 87014247@qq.com

fastcgi设置检测

在html/www下建立phpinfo.php
<?php
phpinfo();
?>
在html/www下建立mysql.php <?php
    $link_id=mysql_connect('192.168.0.80','root','rootabcd') or mysql_error();
        if($link_id){
        echo "mysql successful by gtms !";
    }else{
        echo mysql_error();
    }
?>



fastcgi设置
#cat /usr/local/nginx/conf/extra/www.conf server { listen 80; server_name www.gtms.org; root html/www; location / { index index.html index.htm; } location ~ .*.(php|php5)?$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi.conf; } }

# /usr/local/nginx/sbin/nginx -t
# /usr/local/nginx/sbin/nginx -s reload


测试ok

网站安全设置
# chown -R root.root blog/
upload server(上传目录权限放给nginx)
# find ./blog/ -type f|xargs chmod 644
# find ./blog/ -type d|xargs chmod 755 

PHP5.6.22 安装

yum install zlib-devel libxml2-devel libjpeg-turbo-devel libiconv-devel -y
yum install freetype-devel libpng-devel gd-devel libcurl-devel libxslt-devel -y

mkdir -p /home/tools
cd /home/tools
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.14.tar.gz
tar zxf libiconv-1.14.tar.gz
cd libiconv-1.14
./configure --prefix=/usr/local/libiconv
make
make install
cd ../

wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
yum -y install libmcrypt-devel mhash mhash-devel mcrypt -y


PHP5.6.22:
yum install openssl-devel -y
tar xf php-5.6.22.tar.gz
cd php-5.6.22
./configure 
--prefix=/usr/local/php5.6.22 
--with-mysql=mysqlnd  
--with-pdo-mysql=mysqlnd 
--with-mysqli=mysqlnd
--enable-opcache --with-iconv-dir=/usr/local/libiconv --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-fpm --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-soap --enable-short-tags --enable-static --with-xsl --with-fpm-user=nginx --with-fpm-group=nginx --enable-ftp make make install ln -s /usr/local/php5.6.22/ /usr/local/php server { listen 80; server_name blog.gtms.org; root html/blog; location / { index index.html index.htm; } location ~ .*.(php|php5)?$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi.conf; } }
原文地址:https://www.cnblogs.com/gtms/p/6603157.html