Nginx介绍

nginx是个web服务器程序,本身能够提供web服务功能

支持静态文件,支持httphttps协议,支持虚拟主机等等

nginx性能稍好,但是相对于apache的诸多模块,nginx略显不足

 

nginxhttp协议的反向代理(reverseproxy),类似于DNAT

nginx使用场景更多是反向代理,并且nginx自己有缓存功能(cache),可以加速反向代理,简单负载均衡以及容错,能够实现跟PHP应用服务器结合但是基于CGI的场景并不多,而且性能稍差

 

nginx服务静态文件时,有apache无法比拟的性能优势,如果nginx能满足需要则建议使用nginx

支持sendfilesendfile使响应报文在内核内存中封装响应,这有利于提高nginx读写性能

10000个非活跃的HTTP keep-alive连接仅占用2.5M内存;

nginx官网:www.nginx.org

Nginx安装

编译安装nginx

除编译包组外Nginx依赖pcre-devel    #yum –y install pcre-devel

使用普通用户管理,    #groupadd –r nginxuseradd –r –g nginx nginx

编译选项:

 --prefix=/usr     #指定安装路径

 --sbin-path=/usr/sbin/nginx    #sbin路径

 --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    #pid文件

 --lock-path=/var/lock/nginx.lock   #锁文件

 --user=nginx    #s属主

 --group=nginx    #属组

 --with-http_ssl_module   #启用ssl模块

 --with-http_flv_module   #启用flv模块,流媒体

 --with-http_stub_status_modul   #

 --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

 

make && make install

 

vim /etc/rc.d/init.d/nginx

#插入脚本(可选)

 

添加执行权限 chmod+x /etc/rc.d/init.d/nginx

修改启动项  chkconfig –add nginx

启动服务  service nginx start

Ps –aux查看进程,  ss –tanl 查看监听端口

 

Nginx配置

配置文件/etc/nginx/nginx.conf

全局配置

core

error_log syslog:server=192.168.1.1debug;   #错误日志发往日志服务器

events {       #设定nginx工作模式及连接上限

use epoll;     #连接事件的处理机制,默认不需指定,nginx自行选用

worker_connections  1024   #连接数限定,默认512

}   

worker processes [number | auto]   #定义worker进程的个数

       clients= worker_connections * work_processes

 

worker_cpu_affinity cpumask [0001 0010 0100…];#通过cpumask设置工作于cpu哪个核心

worker_rlimit_nofile 51200;

user nginx nginx;     #指定用户和组

worker_priority [-20 - 20];  #worker优先级,数值越小优先级越高

 

 

nginx上下文四件套

http {

       http段通用于各server的指令;

       server{

<directiv> <value>;

Location {

       if { 

}

}

}

}

http常用指令

root /path/to/   #定义文件访问路径,可以应用于http,server,location范围越小优先级越高

index index.html;  用于http,server,location

include mime.types;

default_type  application/octet-stream;   #定义默认mime类型

log_format     #定义日志格式

access_log #定义日志路径、名称和格式,也可以发往日志服务器或者关闭日志

sendfile on;   #

keepalive_timeout  10;   #启用keepalive并且指定超时时长

add header    #添加报文首部,可用于http,server,location

server  #每个server定义一个虚拟主机

 

server常用指令

listen address[:port];  #监听地址和端口,默认为 *:80 | *:8000之一;

server_name HOSTNAME;   #定义虚拟主机名称

root /path/to/    #定义路径

error_page 404  /404.html   #自定义错误信息和对应的错误文件

rewrite regex replacement[last|break|redirect|permanent]   #重写url,用于serverlocationif

 

 

location常用指令

location [ = | ~ | ~* | ^~ ] uri { 

# /  没有其它符号,限定访问路径从/开始

# = 精确匹配路径,只限定等号所跟的路径

# ~ 模式匹配,后面可跟正则表达式匹配的路径,区分大小写

# ~* 模式匹配,不区分大小写

# ^~ 不做模式匹配,

如果多个出现,越精确优先级越高

}

alias #路径别名

autoindex on   #开启索引,通常关闭,除非提供下载站点

autoindex localtime   #以本地时间显示文件时间,默认开启

autoindex exact size   #显示文件大小,默认开启

stub_status on  #可获取nginx当前处理的连接数等信息

 

if使用,if直接使用在serverlocation中,不可以直接在http中使用

if (condition) {

       rewrite

       set    #自定义变量

       return403

       …

}

 

局部配置示例

定义虚拟主机:

server {

       listen192.168.1.1;

       server_nameabc;

       root//web/vhost1;

       access_logoff;

}

 

IP地址的访问控制:access模块

location / {

       deny192.168.1.1;

       allow192.168.1.0/24;

       allow10.1.1.0/16;

       denyall;

}

 

用户名密码访问控制:auth_basic,使用htpasswd命令定义用户和密码及加密模式等

htpasswd –c –m /etc/nginx/.htpasswdtom   # -m选项使用MD5加密,-c创建文件

New password #输入密码                          添加第二个用户不需要-c选项

location / {

       root/web/vhost1;

       auth_basic“discription words”;

       auth_basic_user_file/etc/nginx/.htpasswd;

}

 

重写url

server {

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

       rewrite^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra last;

       return403;

       …

}

if ($request_uri ~* \.(jpg|png|gif)$) {

  rewrite…

}

if ($host == “www.nginx.com” ) {

   return 403

}

if ($remote_addr == “192.168.1.1”) {

   return 404

}

 

https server

server {

       listen443;

       server_namelocalhost;

       sslon;

       ssl_certificate  cert.pem;

       ssl_certificate_key   cert.key;

       ssl_session_timeout  5m;

       ssl_protocolsSSLv2  SSLv3  TLSv1;

       ssl_ciphersHIGH:!aNULL:!MD5;

       ssl_prefer_server_ciphers  on;

 

       location/ {

root  /web/htdocs;

index index.phpindex.html index.htm;

}

}

LNMP/LNMMP

Linux+Nginx+Mysql+Php(+memcached)

环境:’ServerPlatform Development’ ‘Development tools’ ‘ X Software Development‘

安装mysql

mkdir –pv /mydata/data

useradd –r mysql

tar xf mysql-5.x-linux.tar.gz –C /usr/local

cd /usr/local

ln –sv mysql-5.x-linux mysql

cd mysql

chown –R root:mysql ./*

chown –R mysql:mysql /mydata/data

./scripts/mysql_install_db –user=mysql –datadir=/mydata/data

cp support-files/my-large.cnf  /etc/my.cnf

vim /etc/my.cnf        #没有就添加

datadir = /mydata./data   

innodb_file_per_table = 1

:wq

cp support-files/mysql.server /etc/rc.d/init.d/mysqld

chkconfig –add mysqld

service mysqld start

安装php

可扩展选项:

libmcrypt

mhash

mcrypt

yum –y install mhash-devel libmcrypt-develbzip2-devel libxml2-devel libcurl-devel

tar xf php-5.x.tar.bz2

cd php-5.x

./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-mhash --with-mcrypt  --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脚本,并将其添加至服务列表:

# cp sapi/fpm/init.d.php-fpm  /etc/rc.d/init.d/php-fpm

# chmod +x /etc/rc.d/init.d/php-fpm

# chkconfig --add php-fpm

# chkconfig php-fpm on

 

php-fpm提供配置文件:php-fpmPHPfastcgi管理器

# cp/usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf

 

编辑php-fpm的配置文件:

# vim /usr/local/php/etc/php-fpm.conf

配置fpm的相关选项为你所需要的值,并启用pid文件(如下最后一行):

pm.max_children = 150

pm.start_servers = 8

pm.min_spare_servers = 5

pm.max_spare_servers = 10

pid = /usr/local/php/var/run/php-fpm.pid

 

接下来就可以启动php-fpm了:

# service php-fpm start

 

使用如下命令来验正(如果此命令输出有中几个php-fpm进程就说明启动成功了):

# ps aux | grep php-fpm

整合nginxphp5

 

1、编辑/etc/nginx/nginx.conf,启用如下选项:

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;

       }

 

2、编辑/etc/nginx/fastcgi_params,将其内容更改为如下内容:

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;

fastcgi_param  SERVER_SOFTWARE    nginx;

fastcgi_param  QUERY_STRING       $query_string;

fastcgi_param  REQUEST_METHOD     $request_method;

fastcgi_param  CONTENT_TYPE       $content_type;

fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;

fastcgi_param  REQUEST_URI        $request_uri;

fastcgi_param  DOCUMENT_URI       $document_uri;

fastcgi_param  DOCUMENT_ROOT      $document_root;

fastcgi_param  SERVER_PROTOCOL    $server_protocol;

fastcgi_param  REMOTE_ADDR        $remote_addr;

fastcgi_param  REMOTE_PORT        $remote_port;

fastcgi_param  SERVER_ADDR        $server_addr;

fastcgi_param  SERVER_PORT        $server_port;

fastcgi_param  SERVER_NAME        $server_name;

 

并在所支持的主页面格式中添加php格式的主页,类似如下:

location / {

           root   html;

           index  index.php index.htmlindex.htm;

       }

       

而后重新载入nginx的配置文件:

# service nginx reload

 

3、在/usr/html新建index.php的测试页面,测试php是否能正常工作:

# cat > /usr/html/index.php << EOF

<?php

phpinfo();

?>

 

接着就可以通过浏览器访问此测试页面了。

 

https访问,ssl加密

创建自签证书

cd /etc/pki/CA/

(umask 077;openssl genrsa 2048 >private/cakey.pem)

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

 

touch index.txt

echo 01 > serial

cd /etc/nginx

mkdir ssl

cd ssl/

openssl genrsa 1024 > nginx.key

chmod go-r nginx.key

openssl –req –new –key nginx.key –outnginx.csr

此处输入主机名后应在hosts里面解析

 

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

vim ../nginx.conf

添加虚拟主机参考上文的httpsserver

修改pemkey两个文件的路径为nginx.crtnginx.key所在路径

注意root路径和index设置

另外需要明确说明.php文件的处理方式,参考nginx.conf.php文件处理

 

这时重启nginx服务应该就可以通过https正常访问了

Nginx reverse proxy反向代理

nginx反向代理

客户端请求访问nginx服务器,然后由nginx代理访问后端服务器,这时候的accesslog所记录的访问信息均是nginx,对于日志分析帮助有限,所以在nginx转发请求时可以使用add_header 或者使用proxy_set_header等修改添加header,并且把请求IP取为clientIP

 

ngx_http_proxy_mode

proxy_pass URI;  #URI访问代理至上游服务器,常用于location

       location/name/ {

proxy_pass http://192.168.1.2/remote/;

}

proxy_set_header   #这里设置只是传送,而web服务器的记录则需要设置web服务器的日志格式,/etc/httpd/conf/httpd.conf      修改格式为:LogFormat  %{X-Real-IP}i

       location/name/ {

proxy_pass http://192.168.1.2/remote/;

proxy_set_header X-Real-IP $remote_addr;

}

 

nginx动静分离

即由nginx代理判断, 将动态请求发送到指定服务器,将静态请求发送至另一台服务器

 

nginx读写分离

即将上传文件转发至其它指定服务器

 

Nginx负载均衡

nginx负载均衡

upstream模块将多台服务器定义在一组backend中,由下面的proxy_pass轮着或随机调用

从而做到多台服务器负载均衡。

upstream只能定义在http中,但是可以在serverlocation中引用

upstream backend {      #backend为组名,自定义后在下文中引用
    server backend1.example.com       weight=5;
    server backend2.example.com:8080;
    server unix:/tmp/backend3;
 
    server backup1.example.com:8080   backup;
    server backup2.example.com:8080   backup;
}
 
server {
    location / {
        proxy_pass http://backend;
    }
}

 

upstream模块常用的指令有:

ip_hash:基于客户端IP地址完成请求的分发,它可以保证来自于同一个客户端的请求始终被转发至同一个upstream服务器;

keepalive:每个worker进程为发送到upstream服务器的连接所缓存的个数;

least_conn:最少连接调度算法;

server:定义一个upstream服务器的地址,还可包括一系列可选参数,如:

       weight:权重;

       max_fails:最大失败连接次数,失败连接的超时时长由fail_timeout指定;

       fail_timeout:等待请求的目标服务器发送响应的时长;

       backup:用于fallback的目的,所有服务均故障时才启动此服务器;

       down:手动标记其不再处理任何请求;

健康状态监测

health check

 proxy_cache

缓存通常为分级管理

按次序创建很多子目录,每个子目录按次序存放数据

子目录的字符用十六进制字符来表示,

所以一个字符命名就有16个子目录,2个字符就有256个子目录

创建缓存除了数据之外还应该缓存键,

为了追求对键的快速查找,我们在内存中定义区域来存放键

在磁盘中定义区域来存储缓存对象

为了确保私有信息不被缓存,避免公共缓存风险,通常含有cookie的响应报文不被缓存

 

proxy_cache_path /data/nginx/cachelevels=1:2 keys_zone=one:10mmax_size=1g;

定义缓存响应报文的目录,级别,子目录个数,内存区域及缓存大小等等

 

proxy_cache_min_uses 

为避免不必要缓存,此模块定义响应报文被缓存之前至少应该被请求的次数

 

proxy_cache_use_stale

在无法联系到upstream服务器时的哪种情形下(errortimeouthttp_500)nginx使用本地缓存的过期的缓存对象直接响应客户端请求;其格式为:

proxy_cache_use_stale error | timeout |invalid_header | updating | http_500 | http_502 | http_503 | http_504 |http_404 | off

 

proxy_cache_valid [ code ...] time

用于为不同的响应设定不同时长的有效缓存时长,例如:proxy_cache_valid  200302  10m;

 

proxy_cache_methods [GET HEAD POST]

为哪些请求方法启用缓存功能;

proxy_cache_bypass string:设定在哪种情形下,nginx将不从缓存中取数据;例如:

proxy_cache_bypass $cookie_nocache$arg_nocache $arg_comment;

proxy_cache_bypass $http_pragma$http_authorization;

 

 

nginx/haproxy/squid/varnish

 

四个工具都具有代理和缓存功能

nginx异步代理功能可以大大降低后端服务器压力,

所以通常使用nginx做反向代理,两个节点做高可用

多台varnish做缓存服务器

 

FastCGI

fastcgi协议取得的内容也可以缓存,缓存使用fastcgi_cache_path定义,用法与proxy_cache_path类似,定义在全局或者http中,在serverlocation中用fastcgi_cache 后跟所定义名称启用。

 

Nginx常见知识补充:

open_log_file_cache max=1000 inactive=20svalid=1mmin_uses=2;

日志文件缓存设置模块

nginx命令行参数

       -t测试配置文件语法

       -s[stop|quit|reopen|reload]

平滑升级

       kill–SIGUSER2 <master_process_id>

日志轮换

       -sreopenkill -SIGUSER1<master_process_id>

流量限制

 

ab –c 100 –n 2000 http://192.168.1.1/index.php模拟测试

 

 

 

 

 

 

 

更多nginx模块介绍参见nginx.org/wiki