Nginx是一款高性能的HTTP和反向代理服务器软件javascript
Nginx的优势css
Nginx由内核和模块组成html
模块的分类:前端
Nginx的安装与配置java
1.安装gcc,openssl-devel,pcre-devel和zlib-devel软件库node
zlib-devel软件库,为了gziplinux
[root@localhost ~]# yum install gcc openssl-devel zlib-develnginx
从网上下载pcre-devel软件,为了重写rewriteweb
[root@localhost src]#tar zxvf pcre-8.39.tar.gz正则表达式
[root@localhost src]# cd pcre-8.39
[root@localhost pcre-8.39]# ./configure --prefix=/usr/local/pcre
[root@localhost pcre-8.39]#make
[root@localhost pcre-8.39]#make install
2.安装Nginx
添加用户和组
[root@localhost src]# groupadd -r nginx
[root@localhost src]# useradd -r -g nginx nginx
下载nginx
[root@localhost src]# tar nginx-1.10.1.tar.gz
[root@localhost src]# cd nginx-1.10.1
[root@localhost nginx-1.10.1]#./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/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_mp4_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=/usr/local/src/pcre-8.39
[root@localhost nginx-1.10.1]#make
[root@localhost nginx-1.10.1]#make install
[root@localhost nginx-1.10.1]#mkdir -p /var/tmp/nginx/{client,proxy,fastcgi,uwsgi,scgi}
[root@localhost nginx-1.10.1]#/usr/local/nginx/sbin/nginx -V #查看安装nginx时的编译选项
编译选项解释
--prefix=/usr/local/nginx:安装目录
--sbin-path=/usr/local/nginx/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:pid文件
--lock-path=/var/lock/nginx.lock:lock锁定文件
--user=nginx:程序运行时的非特权用户
--group=nginx:程序运行时的非特权用户组
--with-http_ssl_module:启用ngx_http_ssl_module支持,支持https请求
--with-http_flv_module:提供寻求内存使用基于时间的偏移量文件
--with-http_mp4_module:支持mp4
--with-http_stub_status_module:获取nginx自上次启动以来的工做状态
--with-http_gzip_static_module:在线实时压缩输出数据流
--http-client-body-temp-path=/var/tmp/nginx/client/:设定http客户端请求临时文件路径
--http-proxy-temp-path=/var/tmp/nginx/proxy/:设定http代理临时文件路径
--http-fastcgi-temp-path=/var/tmp/nginx/fcgi/:设定http fastcgi临时文件路径
--http-uwsgi-temp-path=/var/tmp/nginx/uwsgi:设定http uwsgi临时文件路径
--http-scgi-temp-path=/var/tmp/nginx/scgi:设定http scgi临时文件路径
--with-pcre:启用pcre库
其余编译选项
–with-pcre= 指向pcre库文件目录
–with-md5= 指向md5库文件目录
–with-sha1= 指向sha1库目录
–with-zlib= 指向zlib库目录
–with-openssl= 指向openssl安装目录
–with-debug 启用debug日志
–with-mail 启用POP3/IMAP4/SMTP代理模块支持
–with-http_secure_link_module:计算和检查要求所需的安全连接网址
–with-http_degradation_module:容许在内存不足的状况下返回204或444码
3.Nginx的配置文件
Nginx主配置文件,/etc/nginx/nginx.conf
Nginx的主配置文件分为4个部分:main(全局设置),server(主机设置),upstream(负载均衡服务器设置),location(URL匹配特定位置的设定)
(1)Nginx的全局配置
user nobody;
worker_processes 4;
error_log logs/error.log notice;
pid logs/nginx.pid;
worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 1024;
}
user nobody nobody; 指定Nginx Worker进程运行用户以及用户组,默认为nobody
worker_processes 4; 指定Nginx要开启的进程数
error_log; 定义全局错误日志文件
pid; 指定进程id的存储文件位置
worker_rlimit_nofile 65535; 用于绑定worker进程和cpu
events 用来设定Nginx的工做模式及链接数上限
use 用来指定nginx的工做模式,select和poll是标准的工做模式,kqueue和epoll是高效的工做模式,kqueue用在BSD系统,linux系统epoll是首选
worker_connections 用于定义nginx每一个进程的最大链接数,默认是1024
(2)HTTP服务器的配置
http {
include conf/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"';
client_max_body_size 20m;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
client_header_timeout 10;
client_body_timeout 10;
send_timeout 10;
include 设定mime类型,类型由mime.type文件定义
default_type 默认类型为二进制流
log_format 指定nginx日志的输出格式
$remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;
$remote_user:用来记录客户端用户名称;
$time_local: 用来记录访问时间与时区;
$request: 用来记录请求的url与http协议;
$status: 用来记录请求状态;成功是200,
$body_bytes_sent :记录发送给客户端文件主体内容大小;
$http_referer:用来记录从那个页面连接访问过来的;
$http_user_agent:记录客户浏览器的相关信息;
client_max_body_size 设置容许客户端请求的最大单个文件字节数
client_header_buffer_size 指定来自客户端请求头的headerbuffer大小
large_client_header_buffers 指定客户端请求中较大的消息头的缓存最大数量和大小
sendfile 开启高效文件传输模式
tcp_nopush 防止网络堵塞
tcp_nodelay 防止网络堵塞
keepalive_timeout 客户端链接保持活动的超时时间
client_header_timeout 客户端请求头读取超时时间
client_body_timeout 客户端请求主体读取超时时间
send_timeout 响应客户端的超时时间
(3)HttpGzip模块,支持在线实时压缩输出数据流
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
gzip 用于设置开启或者关闭gzip
gzip_min_length 容许压缩的页面最小字节数
gzip_buffers 申请4个单位为16k的内存做为压缩结果流缓存
gzip_http_version 识别HTTP协议版本,默认1.1
gzip_comp_level 指定gzip压缩比
gzip_types 指定压缩的类型
gzip_vary 让前端的缓存服务器缓存通过gzip压缩的页面
(4)负载均衡配置
upstream ixdba.net{
ip_hash;
server 192.168.1.123:80 weight=3;
server 192.168.1.124:80 down;
server 192.168.1.125:8009 max_fails=3 fail_timeout=20s;
server 192.168.1.126:8080;
}
经过upstream 指定一个负载均衡器的名称ixdba.net
负载均衡模块调度算法
轮询:默认,每一个请求按时间顺序逐一分配到不一样的后端服务器
weight:weight越大,分配到的访问机率越高
ip_hash:每一个请求按访问ip的hash结果分配
fair:依据页面大小和加载时间长短智能的进行负载均衡
url_hash:按访问url的hash结果来分配请求
服务器在负载均衡调度中的状态
down:表示暂时不参与负载均衡
backup:预留的备份机器
max_fails:容许请求失败的次数
fail_timeout:在经历了请求失败的次数后,暂停服务的时间
(5)虚拟主机的配置
能够配置多个虚拟主机
server{
listen 80;
server_name 192.168.0.100 www.hyundai.com;
index index.html index.htm index.jsp;
root /web/wwwroot/www.hyundai.com
charset gb2312;
server { listen 8001; server_name localhost; location / { root /web/html; index index.html index.htm; } }
listen:监听端口
server_name:指定ip或域名
index:默认首页地址
root:网页根目录
charset:设置网页的默认编码格式
(6)URL匹配配置
Nginx中的location指令是NginxHttpCoreModule中重要指令。Location指令比较简单,也比较经常使用。
location指令,是用来对url进行匹配的,URI即语法中的/uri/,能够是字符串或正则表达式。若是是正则表达,则必须指定前缀。location指令根据URI来应用不一样的配置,这个指令容许根据不一样URI来应用不一样的url配置。
Location语法语法:location [=|~|~*|^~] /uri/ { … }
= --> 开头表示精确匹配
^~ --> 开头表示uri以某个常规字符串开头,理解为匹配url路径便可。
nginx不对url作编码,所以请求为/static/20%/aa,能够被规则^~ /static/ /aa匹配到(注意是空格)。
~ --> 开头表示区分大小写的正则匹配
~* --> 开头表示不区分大小写的正则匹配
!~和!~* --> 分别为区分大小写不匹配及不区分大小写不匹配的正则
/ --> 通用匹配,任何请求都会匹配到。
多个location配置的状况下匹配顺序为:
首先匹配=,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,中止匹配,按当前匹配规则处理请求。
location - .*\.(gif|jpg|jpeg|png|bmp|swf)${
root /web/wwwroot/www.hyundai.com;
expires 30d;
}
把以上这些静态文件交给Nginx处理,expires指定静态文件过时时间为30天
location - ^/(upload|html)/{
root /web/wwwroot/www.hyundai.com;
expires 30d;
}
把upload和html下的全部文件都交给nginx处理
location ~ .*.jsp${
index index.jsp;
proxy_pass http://localhost:8080;
}
全部.jsp文件都交给本机的8080端口处理
4.Nginx的启动和关闭
检查nginx配置文件的正确性
/usr/local/nginx/sbin/nginx -t -c /etc/nginx/nginx.conf
显示以下信息,则说明正确
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
显示nginx的版本信息
/usr/local/nginx/sbin/nginx -v
nginx的启动
/usr/local/nginx/sbin/nginx
查看nginx的启动进程
ps -ef |grep nginx
从新加载配置文件
/usr/local/nginx/sbin/nginx -s reload
5.Nginx开机自动启动
vim /etc/init.d/nginx
#!/bin/bash # # 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/local/nginx/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
chmod a+x /etc/init.d/nginx #添加执行权限
chkconfig --add nginx #添加到服务管理列表
chkconfig nginx on #开机启动
service nginx start
/usr/local/nginx/html #nginx网页根目录
Nginx性能优化技巧
1.减少Nginx编译后的文件大小
编译nginx时,默认以debug模式进行,会插入不少跟踪和ASSERT之类的信息,在编译以前,修改源码,取消debug模式
源码目录下vim auto/cc/gcc,删除或注释如下几行
# debug
CFLAGS="$CFLAGS -g"
2.为特定的CPU指定CPU类型编译优化
优化GCC编译
--with-cc-opt='-O3'
--with-cpu-opt=CPU #为特定的CPU编译
cat /proc/cpuinfo | grep "model name" #肯定CPU类型
nginx反向代理
反向代理(Reverse Proxy)方式是指以代理服务器来接受Internet上的链接请求,而后将请求转发给内部网络上的服务器;并将从服务器上获得的结果返回给Internet上请求链接的客户端,此时代理服务器对外就表现为一个服务器。
公网延迟高,客户端与nginx之间的请求链接走公网,nginx先把这些请求缓存住,等这些请求数据所有完成以后nginx再向内网服务器请求,下降公网网络延迟成本,同时也下降一个链接占用服务端程序的时间。
由于tcp不必定一次就能把所有数据传输完毕,因此一个链接可能须要等待好久才能把全部须要的数据都传输完毕,而这样的空闲链接若是都直接链接到服务器上的话,会加剧服务器负担,而nginx在这方面作了很大的优化,能够承载更多的链接,空闲链接也不会占据太多内存,因此nginx做为反向代理能下降上游服务器的负载。
server { listen 8001; server_name localhost; location / { proxy_pass http://10.3.6.31:8003; } }
proxy_pass:指定反向代理服务器