Nginx的特性:
模块化设计、较好扩展性
高可靠性
master-->worker
低内存消耗
10000个keep-alive连接在Nginx仅消耗2.5MB
支持热部署
不停机而更新配置文件、更换日志文件、更新服务器程序版本
基本功能:
静态资源的web服务器,能缓存打开的文件 描述符
http, smtp, pop3协议的反向代理服务器,缓存、负载均衡;
支持FastCGI (fpm)
模块化,非DSO机制,过滤器zip,SSI及图像大小调整;
支持SSL
扩展功能:
基于名称和IP的虚拟主机;
支持keepalive
支持平滑升级
定制访问日志 ,支持使用日志缓冲区提高日志存储性能
支持url rewrite
支持路径别名
支持基于IP及用户的访问控制
支持速率限制,支持并发数限制
Nginx的基本架构:
一个master进程,生成一个或多个worker
事件驱动: epoll, kqueue, /dev/poll (event ports)
消息通知:select, poll, rt signals
支持sendfile, sendfile64
支持AIO
支持mmap
nginx: 非阻塞、事件驱动、一个master生成一个或多个worker, 每个worker响应n个请求;
模块类型:
核心模块
Standard HTTP modules
Optional HTTP modules
Mail modules
3rd party modules
准备依赖库
yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel
yum -y install pcre pcre-devel
安装方法:
rpm及源码安装:
# ./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --user=nginx --group=nginx --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 --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module
# make && make install
useradd nginx
mkdir -pv /var/tmp/nginx/{client,proxy,fastcgi}
配置文件:
main配置段: 全局配置段
event: 定义event模型配置段
http {}: 定义http协议相关的配置
配置指令要以分号结尾,语法格式:
directive value1 [value2...];
支持使用变量:
模块内置变量
自定义变量
set var_name value
主配置段的指令的类别:
用于调试、定位问题
正常运行必备的配置
优化性能的配置
事件相关的配置
正常运行的必备配置:
1、user USERNAME [GROUPNAME];
指定运行worker进程的用户 和组,例如:
user nginx nginx;s
2、pid /path/to/pid_file;
指定nginx的pid文件;
3、worker_rlimit_nofile #;
指定所有worker进程所能够打开的最大文件句柄数;
优化性能相关的配置:
1、worker_processes #:
worker线程的个数;通常应该为物理CPU核心个数减1;
2、worker_cpu_affinity cpumask ...;
绑定worker进程至指定的CPU上;
CPUMASK
0001
0010
0100
1000
例如:
worker_cpu_affinity 00000001 00000010 00000100;
3、timer_resolution t;
gettimeofday();
默认 100ms //100ms毫秒解析一次, 1000ms一千毫秒解析一次也就是一秒解析一次
4、worker_priority nice;
-20, 19
事件相关的配置:
1、accept_mutex [on|off]
内部调用用户 请求至各worker时用的负载均衡锁;打开时表示能让多个worker轮流地、序列化地与响应新请求;
2、lock_file /path/to/lock_file;
3、accept_mutex_delay #ms; 等待时间
4、use [epoll|rgsig|select|poll];
定义使用的事件模型;建议让Nginx自动选择;
5、worker_connections #;
每个worker进程所能够响应的最大并发请求数;
用于调试、定位问题:
1、daemon [off|on]
是否以守护进程方式启动nginx;
2、master_process on|off;
是否以master/worker模型来运行nginx;
3、error_log /path/to/error_log level;
错误日志文件及其级别;出于调试的目的,可以使用debug级别,但此级别只有在编译nginx时使用了--with-debug选项才有效;
总结 常需要进行调整的参数
worker_processes, worker_connections, worker_cpu_affinity, worker_priority
/usr/local/nginx/sbin/nginx -t 检查配置文件语法
/usr/local/nginx/sbin/nginx -s reload 重载配置文件
/usr/local/nginx/sbin/nginx -s stop 停止
/usr/local/nginx/sbin/nginx -s reopen 重启
nginx:
main配置段
http {
}
http配置:http core 配置一个静态web服务器
ngx_http_core_module
配置框架:
http {
upstream {
.,..
}
server {
listen IP:PORT;
# 虚拟主机
location /URL {
if ...{
...
}
root "/path/to/somewhere";
...
}
}
server {
,,.
}
}
注意:与http配置相关的指令必须放在http、server、location、upstream、if块中;
虚拟主机相关的配置:
1、server {}
定义一个虚拟主机;
2、listen
监听的端口
完整格式 :listen address[:port] [default_server] [ssl] [spdy] [proxy_protocol] [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
listen address[:port] [default_server] ssl
backlog=number: 指明TCP协议backlog队列的大小。默认为-1,表示不设置;
rcvbuf=size:设定监听句柄的SO_RCVBUF参数;
例如:
listen 172.16.100.8:8080
3、server_name name [...];
后可跟多个主机名;名称还可以使用通配符和正则表达式(~);
(1) 先做精确匹配;www.magedu.com:
(2) 左侧通配符匹配,例如:*.magedu.com;
(3) 右侧通配符匹配,例如:www.*;
(4) 正则表达式匹配,例如: ~^.*\.magedu\.com$
(5) default_server
server{
server_name www.magedu.com;
}
server{
server_name *.mail.com;
}
server{
server_name mail.*;
}
4、location [=|~|~*|^~] /uri {...}
location @name
功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location块中的配置所处理;
=: 精确匹配检查;
~: 正则表达式模式匹配,区分字符大小写;
~*:正则表达式模式 匹配,不区分字符大小写;
^~:URI的前半部分匹配,不检查正则表达式;
匹配优先级:精确匹配(=)、^~、~和~*、由不带符号的URL进行左侧匹配;
server{
listen 80;
server_name www.my.com
location / {
root /vhosts/web;
}
location /images/ {
root /vhosts/images;
}
location ~* \.php$ {
fcgipass;
}
#location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
# try_files $uri =404;
#}
}
5、root
设置web资源路径映射;用于指明请求的URL所对应的文档的根目录路径;
location /images/ {
root "/web/imgs/";
}
6、alias path
用于location配置段,定义路径别名
location /images/ {
alias /www/pictures/;
}
注意:root表示指明路径为对应location的“ /” URL;alias表示路径映射,即location中的URL是相对于alias所指明的路径而言;
7、index file
默认主页面
index index.html;
8、error_page code [...] [=code] URI | @name
根据http状态码重定向错误页面
error_page 404 /404.html
=[code]: 以指定的响应码进行响应;省略code表示以新资源的响应码为响应码;
9、 HTTPS server
server {
listen 443 ssl;
server_name localhost;
ssl_certificate cert.pem;
ssl_certificate_key cert.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
10、location /status {
stub_status on;
allow 192.168.0.100;
deny all;
}
Active connections: 1
server accepts handled requests
3667 3667 3738
1 已接受的连接数
2 已经处理的连接数
3 已经处理过的请求数
Reading: 0 Writing: 1 Waiting: 0
reading: 正在接受的连接数
writing: 正在发送相应报文的连接数
waiting: 保持tcp连接的连接数
11、rewrite regex replacement flage
例如: rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
http://www.shop.com/images/a/b/c/1.jpg ---> http://www.shop.com/imgs/a/b/c/1.jpg
80端口到443端口重定向
rewrite ^(.*)$ https://$server_name$1 break;
last 会重新匹配当前server内location,会重复匹配一个location.
break不会重新匹配当前server内任意location. url路径重定向完成之后, 在当前root路径下查找请求文件,break如果重定向到其他server内会匹配其他server内location.
permanent 和 redirect 总结如下:
permanent: 大家公认的信息 ,永久性重定向。请求日志中的状态码为301
redirect: 大家公认的信息 ,临时重定向。请求日志中的状态码为302
12、if语法
if(condition){}
condition:
(1)变量名: 变量为空串, 以字符"0"开头,则为false,其他均为true;
(2)以变量为操作数构成的比较表达式: 可使用 = != 类似的比较操作符进行测试
(3)正则表达式的模式匹配操作 ~, ~*, !~
(4)测试路径为文件可能性: -f, !-f
(5)测试路径为目录可能性: -d, !-d
(6)测试文件存在性: -e, !-e
(7)检查文件是否有执行权限: -x, !-x
例如
if ($http_user_agent ~* MSIE) {
rewrite ^(.*)$ /msie/$1 break;
}
13、防盗链
location ~* \.(jpg|gif|jpeg|png)$ {
valid_referer none blocked www.my.com;
if ($invalid_referer) {
rewrite ^/ http://www.my.com/403.html
}
}
return 200 'wo le ge qu! 返回相应状态码 后面为相应主体即html页面内容
try_files files1 files2 rewrite_uri =404 相对当前root生成文件路径,依次尝试文件是否存在,存在则使用该文件相应,若都不存在则使用最后一个uri重定向, 最后一个若为相应状态码, 则只有相应状态码能引发重定向, 除响应状态码以外, 均为尝试直接使用当前location规则返回存在的文件.
网络连接相关的配置:
1、keepalive_timeout time;
保持连接的超时时长,默认为75s;
2、keepalive_requests #;
在一次保持连接上允许承载最大资源请求数;
3、keepalive_disable [msie6|safari|none]
为指定类型的浏览器禁用长连接;
4、tcp_nodelay on|off
对长连接是否使用TCP_NODELAY选项;
5、client_header_timeout time;
读取http请求报文首部的超时时长;
6、client_body_timeout time;
读取http请求报文body部分的超时时长;
7、send_timeout time;
发送响应报文的超时时长;
对客户端请求进行限制:
1、limit_except METHOD {...}
指定对范围之外的其它方法的访问控制;
limit_except GET {
allow 172.16.0.0/16;
deny all;
}
2、client_body_max_size SIZE;
限制请求报文中body部分的上限;通过检测请求报文首部中的"Content_Length"来判定;
3、limit_rate speed;
限制客户端每秒种传输的字节数,默认为0,表示无限制;
对内存或磁盘资源进行分配
1、client_body_in_file_only on|clean|off;
请求报文的body部分是否可暂存于磁盘;on表示允许,并且即使请求结束,也不会删除暂存的内容;clean表示会删除;off不允许暂存;
2、client_body_in_single_buffer on|off
3、client_body_buffer_size size;
4、client_body_temp_path DIR [level1 [level2 [level3 [level4]]]]
例如:client_body_temp_path /var/tmp/nginx/client 1 2
5、client_header_buffer_size size:
MIME类型相关的配置:
1、types {}
定义MIME types至文件的扩展名;
types {
text/html .html;
image/jpeg .jpg;
}
2、default_type MIME-TYPE;
文件操作优化相关的配置:
1、sendfile on|off;
2、aio on|off;
3、directio size|off;
是否使用O_DIRECT选项去请求读取文件;与sendfile功能互斥;
4、open_file_cache max=N[inactive=time] | off;
nginx可以缓存以下三种信息:
(1) 文件句柄、文件大小和最近一次修改时间;
(2) 打开目录的目录结构;
(3) 没有找到的或者没有权限操作的文件的相关信息;
max=N表示可缓存的最大条目上限;一旦到达上限,则会使用LRU从缓存中删除最近最少使用的条目;
inactive=time: 在inactive指定的时长内没有被访问过的缓存条目就会淘汰;
5、open_file_cache_errors on|off;
是否缓存在文件缓存中缓存打开文件时出现找不到路径,没有权限等的错误信息;
6、open_file_cache_min_uses time;
每隔多久检查一次缓存中缓存条目的有效性;默认60s;
重点关注:server{}, location{}, listen, server_name, root, alias, keepalive_timeout, keepalive_requests, error_page
基于IP的访问控制:
http, server, location
allow, deny
基于用户的basic认证配置:
auth_basic
auth_basic_user_file
htpasswd命令创建用户账号文件;
基于gzip实现响应报文压缩:
定制响应首部
add_header name value [always];
expires
定制访问日志
log_format
access_log
定制出与httpd的combined格式相同的日志内容;
定义合法引用:
valid_referers none | blocked | server_names | string ...;
if ($invalid_referer) {
return 403
}
URL rewrite:
rewrite regex replacement [flag];
last
break
redirect
permanent
if (condition) {
...
}
比较表达式:
=:
!=
~
~*
!~
!~*
-f, !-f
-d, !-d
-e, !-e
-x, !-x
return:
return code URL
set $variable value
总结:nginx
主配置
http
core: server{}, location{},
access
basic
gzip
ssl
rewrite
log
referer
stub_status
headers
session保持方法:
session绑定:sh
session复制:
session服务器:memcached, redis (key-value, kv store)
Nginx的配置:
main, event, http
http {
directive
server {
listen
server_name
location {
if {
}
}
}
server {
}
}
ngx_http_proxy_module模块:
server {
listen
server_name
location /backend/ {
root /www_n;
index index.html index.htm;
proxy_pass http://192.168.43.201/frontend/;
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
匹配到location的路径名映射到后端路径,类似于alias别名,路径替换,后续路径原样转发
若location ~* 正则匹配, 则porxy_pass不可添加url路径;
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
格式:
location /uri {
rewrite
proxy_pass http://back_server:port/newuri;
}
/uri --> /newuri
ngx_http_proxy_module:实现反向代理及缓存功能
proxy_pass http://{SERVER_IP|UPSTREAM_NAME}/uri
proxy_cache_path path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size];
proxy_cache zone_name;
proxy_cache_valid [code] time;
!必须定义此值才能正常启用缓存!相应相应状态码缓存时间 200 1d // 200ok 缓存一天
proxy_cache_method //缓存那种请求, 默认 get, head
proxy_cache_use_stale error timeout ... //后端服务器不可用时,是否使用过期缓存 off | timeout
proxy_cache_min_uses //定义请求多少次会被缓存
proxy_cache_revalidate on | off // 在缓存过期时,询问后端服务器资源是否改变
proxy_cache_bypass string: 设置在何种情形下nginx将不从cache取数据的;
$cookie_nocache $arg_nocache $http_authorization
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_connect_timeout: 向上有服务器转发时连接超时时长
proxy_hide_header: 隐藏上游服务器的header, 但不能隐藏其自身
server_tokens off; 隐藏nginx版本信息;
ngx_http_upstream_module:
定义服务器组
proxy_pass, fastcgi_pass, uwsgi_pass,
//只能在http段被定义
upstream name {
server address [parameters];
ip_hash;
}
upstream myhosts {
server 192.168.43.201:80;
hash $request_uri consistent;
}
upstream backend {
server backend1.example.com:12345 weight=5;
server 127.0.0.1:12345 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend2;
server backend3.example.com:12345 resolve;
server backup1.example.com:12345 backup;
}
location / {
proxy_pass http://myhosts/;
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
负载均衡调度算法;
基于sticky实现session绑定:
cookie
route
learn ()
ip_hash
least_conn: 调度方法,最少连接;
//商业版才有,社区版没有
health_check;
建议:关闭访问日志;
自定义响应首部:
add_header X-Via $server_addr;
add_header X-Cache $upstream_cache_status;
LNMP
fpm
编辑/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;