Nginx

介绍
Nginx是lgor Sysoev为俄罗斯访问量第二的rambler.ru站点设计开发的。从2004年发布至今,凭借开源的力量,已经接近成熟与完善。
Nginx功能丰富,可作为HTTP服务器,也可作为反向代理服务器,邮件服务器。支持FastCGI、SSL、Virtual Host、URL Rewrite、Gzip等功能。并且支持很多第三方的模块扩展。
官方:http://www.nginx.org/
常用功能
web服务器
web缓存服务器
反向代理:四层代理(stream)和七层代理
负载均衡:upstream
工作原理
Nginx由内核和一系列模块组成,内核提供web服务的基本功能,如启用网络协议,创建运行环境,接收和分配客户端请求,处理模块之间的交互。Nginx的各种功能和操作都由模块来实现。Nginx的模块从结构上分为核心模块、基础模块和第三方模块。
1)核心模块: HTTP模块、EVENT模块和MAIL模块
2)基础模块: HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块
3)第三方模块: HTTP Upstream Request Hash模块、Notice模块和HTTP Access Key模块及用户自己开发的模块
安装
1.下载阿里源的EPEL源仓库
[root@node1 ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
2.安装nginx
[root@node1 ~]# yum install nginx -y
[root@node1 ~]# nginx -v
nginx version: nginx/1.12.2
3.启动服务,并测试
[root@node1 ~]# systemctl start nginx.service
[root@node1 ~]# echo “hello” > /usr/share/nginx/html/index.html
[root@node1 ~]# httpd -s reload
[root@node1 ~]# curl 192.168.0.140
hello
默认主配置文件
[root@node1 ~]# cat /etc/nginx/nginx.conf
user nginx; # 运行用户
worker_processes auto; # 启动进程,通常和cpu数量一致
error_log /var/log/nginx/error.log; # 错误日志
pid /run/nginx.pid; # PID文件

Load dynamic modules. See /usr/share/nginx/README.dynamic.

include /usr/share/nginx/modules/*.conf; # 加载动态模块

工作模式

events {
#use epoll; # 事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
worker_connections 1024; # 单个进程的连接数
}
http全局配置
http {
# 日志格式
log_format main '$remote_addr - r e m o t e u s e r [ remote_user [ remoteuser[time_local] “KaTeX parse error: Double superscript at position 34: … '̲status b o d y b y t e s s e n t " body_bytes_sent " bodybytessent"http_referer” ’
‘“ h t t p u s e r a g e n t " " http_user_agent" " httpuseragent""http_x_forwarded_for”’;
access_log /var/log/nginx/access.log main; # 访问日志
sendfile on; # 允许sendfile方式传输文件
tcp_nopush on; # 在sendfile启动下,使用TCP_CORK套接字
tcp_nodelay on; # 接连接保持活动状态
keepalive_timeout 65; # 连接超时时间,默认为65s
types_hash_max_size 2048; # 设置类型哈希表的最大大小
include /etc/nginx/mime.types; # 文件扩展名与文件类型映射表
default_type application/octet-stream; # 默认文件类型,默认为text/plain
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/.conf;
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html; # 根目录
# Load configuration files for the default server block.
include /etc/nginx/default.d/
.conf;
根据请求URI设置配置
location / {
}
error_page 404 /404.html; # 错误页
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}

Settings for a TLS enabled server.

server {

listen 443 ssl http2 default_server;

listen [::]:443 ssl http2 default_server;

server_name _;

root /usr/share/nginx/html;

ssl_certificate “/etc/pki/nginx/server.crt”;

ssl_certificate_key “/etc/pki/nginx/private/server.key”;

ssl_session_cache shared:SSL:1m;

ssl_session_timeout 10m;

ssl_ciphers HIGH:!aNULL:!MD5;

ssl_prefer_server_ciphers on;

# Load configuration files for the default server block.

include /etc/nginx/default.d/*.conf;

location / {

}

error_page 404 /404.html;

location = /40x.html {

}

error_page 500 502 503 504 /50x.html;

location = /50x.html {

r e m o t e a d d r 和 remote_addr和 remoteaddrhttp_x_forwarded_for:用来记录客户端的IP地址
$remote_user:用来记录客户端用户名称
$time_local:用来记录访问时间与时区
$request:用来记录请求的url与http协议
$status:用来记录请求状态:成功是200
$body_bytes_sent:记录发送给客户端文件主体内容大小
$http_referer:用来记录从哪个页面链接访问过来的
KaTeX parse error: Expected '}', got '#' at position 64: …ocation / { #̲ 根据请求URI设定配置 ~… {
[ configuration E ]
}
A:请求 /
B: 请求 index.html
C: 请求 /documents/document.html
D: 请求 /images/1.jpg
E: 请求 /documents/document.gif
配置指令1
正常运行相关配置
user # 运行用户
pid # 指定nginx主进程存储位置
include # 包含进来的其他配置片段
load_module file # 指明要装载的动态模块
优化性能相关的配置
worker_process
worker_cpu_affinity # cpu绑定
worker_priority # 指明work进程nice值
worker_rlimit_nofile # 进程所能打开的文件数量上限
用于调试及定位问题相关配置
daemon # 是否以守护进程方式运行Nginx
master_process # 是否以master/worker模型运行nginx
error_log # 错误日志
事件驱动相关配置
events{…} # 配置事件驱动
worker_connections # 每个work进程的最大并发连接数
use # 指明并发连接请求的处理方法
accept_mutex # 处理新的连接请求的方法;轮询|所有
配置指令2
套接字相关配置
server{…} # 配置一个虚拟主机
listen # 设置监听端口
server_name # 指定虚拟主机的主机名称
tcp_nodelay # 在keepalived模式下的连接是否启用TCP_NODELAY选项
tcp_nopush # 在sendfile模式下,是否启用TCP_CORK选项
sendfile # 是否启用sendfile功能
定义路径相关配置
root # 设置web资源映射的根目录路径
location # 可以存在多个
alias # 定义别名
index # 默认资源
try_file # 判断指定目录文件是否存在
客户端请求相关配置
keepalive_timeout # 保持连接的超时时长
keepalive_requests # 一次连接允许请求资源的最大数量
keepalive_disable # 对某种浏览器禁用长连接
send_timeout # 向客户端发送响应报文的超时时长
client_body_buffer_size # 接收客户端请求报文的body部分的缓冲区大小
client_body_temp_path # 设定用于存储客户端请求报文的body部分的临时存储路径及子目录结构和数量
客户端限制相关配置
limit_rate rate # 限制响应给客户端的传输速率
limit_except # 限制对指定的请求方法之外的其它方法的使用客户端
文件操作优化相关配置
aio # 是否启动aio功能
directio # 在Linux主机启用O_DIRECT标记
open_file_cache #
open_file_cache_valid time #
open_file_cache_min_uses number #
open_file_cache_errors #
Http相关模块介绍
ngx_http_core_module模块:
核心模块:
alias
aio
keepalive_disable
keepalive_request
keepalive_timeout
server
sever_name
sendfile
send_timeout
……
ngx_http_access_module模块:实现基于IP的访问控制功能
allow:允许访问的IP
deny:拒绝访问的IP
Example
location / {
include /path/to/whilelist;
deny all;
}
针对请求url为: 192.168.10.10/
address | CIDR | unix: | all;
include whilelist:
whilelist文件:
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
ngx_http_auth_basic_module模块:实现基于用户的访问控制,使用basic机制进行用户认证
Example:
location / {
auth_basic “closed site”; 认证提示说明
auth_basic_user_file conf/htpasswd;定义认证文件
}
htpasswd:
zhaohao:md5的password
格式:
#comment
name1:password1
name2:password2:comment
name3:password3
ngx_http_stub_status_module模块:用于输出nginx的基本状态信息
Example:
location = /basic_status { # 精确匹配
stub_status;
}
最后网页输出:
Active connections:291
Server accepts handled requests
16630948 16630948 31070465
Reading:6 Writing:179 Waiting:106
ngx_http_log_module模块:定义相关日志的设置
access_log 定义访问日志
log_format 定义日志格式
open_log_file_cache 定义一个缓存,用于存储名称中包含变量的常用日志的文件描述符
ngx_http_gzip_module模块:是一个使用“gzip”方法压缩响应的过滤器
Example:
gzip on;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain application/xml;

ngx_http_ssl_module模块:定义https相关配置
ngx_http_rewrite_module模块:将用户请求的URI基于regex所描述的模式进行检查,而后完成替换
Example:
}
Nginx反向代理和缓存
介绍
反向代理(Reverse Proxy)方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器,通常使用到的http/https协议和fastgci(将动态内容和http服务器分离)
ngx_http_proxy_module模块
代理相关模块及配置
nginx代理基于ngx_http_proxy_module模块的功能,该模块有很多属性配置选项:
proxy_pass:指定将请求代理至server的URL路径;
proxy_set_header:将发送至server的报文的某首部进行重写;
proxy_send_timeout:设置将请求传输到代理服务器的超时。仅在两次连续写入操作之间设置超时,而不是为整个请求的传输。
proxy_read_timeout:定义从代理服务器读取响应的超时。仅在两个连续的读操作之间设置超时
proxy_connect_timeout: 定义与代理服务器建立连接的超时
缓存相关模块及配置
proxy_cache_path:定义可用于proxy功能的缓存
proxy_cache zone:指明要调用的缓存,或关闭缓存机制
proxy_cache_valid:定义对特定响应码的响应内容的缓存时长;
proxy_cache_use_stale
proxy_cache_methods
proxy_hide_header
proxy_connect_timeout
proxy_read_timeout
proxy_send_timeout
基于http协议代理和缓存实验:
node1作为代理服务器
node2作为lamp服务器
[root@node1 ~]# cat /etc/nginx/nginx.conf
http{

proxy_cache_path /var/cache/nginx/proxy_cache levels=1:1:1 keys_zone=pxycache:20m max_size=1g
}
[root@node1 ~]# cat /etc/nginx/conf.d/proxy.conf
server{
server_name 172.16.0.10;
location / {
proxy_pass http://192.168.10.20;
proxy_set_header X-Real-IP $remote_addr;
proxy_send_timeout 75s; # 默认60s
proxy_read_timeout 75s; # 默认60s
proxy_connect_timeout 75; # 默认60s
proxy_cache pxycache;
proxy_cache_key $request_uri;
proxy_cache_valid 200 302 301 1h;
proxy_cache_valid any 1m;
}
}
[root@node2 ~]# cat /etc/httpd/conf/httpd.conf | grep log
LogFormat “”%{X-Real-IP}i" %h %l %u %t “%r” %>s %b “%{Referer}i” “%{User-Agent}i”" combined
测试:
1.打开浏览器访问http://172.16.0.10/index.html和index.php
2.查看node2的httpd服务日志X-Real-IP头部
3.查看node1上的cache目录下缓存内容

ngx_http_headers_module模块
向由代理服务器响应给客户端的响应报文添加自定义首部,或修改指定首部的值
add_header name:添加自定义首部
expires:用于定义Expire或Cache-Control首部的值
ngx_http_fastcgi_module模块
代理相关模块及配置
fastcgi_pass address:定义fastcgi server的地址
fastcgi_index name:定义fastcgi默认的主页资源
fastcgi_param:设置应传递给FastCGI服务器的参数
缓存相关模块及配置
fastcgi_cache_path
fastcgi_cache
fastcgi_cache_key
fastcgi_cache_methods
fastcgi_cache_min_uses
fastcgi_cache_valid
fastcgi_keep_conn
基于fgci协议代理和缓存实验:
node1为代理服务器
node2为lnmp服务器
[root@node1 ~]# cat /etc/nginx/nginx.conf
http{

fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2:1 keys_zone=fcgi:20m inactive=120s;
}
[root@node1 conf.d]# cat proxy.conf
server{
server_name 172.16.0.10;
location / {
proxy_pass http://192.168.10.20;
}
# 实现动静分离
location ~ ..(html|txt)$ {
root /usr/share/nginx/html/;
}
# 缓存相关配置
location ~
.php$ {
fastcgi_cache fcgi;
fastcgi_cache_key KaTeX parse error: Expected 'EOF', got '}' at position 115: …_valid any 1m; }̲ [root@node2 ~]… {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
include fastcgi_params;
}
}
测试:
1. 访问http://172.16.0.10/index.html 和 index.php
2. 查看node1上的cache目录下缓存内容
课后作业:
整理ngx_http_proxy_module
缓存相关配置项:
proxy_pass URL;
#设置代理服务器的协议和地址以及应映射位置的可选URI。作为协议,可以指定“http”或“https”。地址可以指定为域名或IP地址,以及可选端口:
proxy_hide_header field;
#默认情况下,nginx不会从代理服务器对客户端的响应中传递标题字段“Date”,“Server”,“X-Pad”和“X-Accel -…”。 proxy_hide_header指令设置了不会传递的其他字段。相反,如果需要允许传递字段,则可以使用proxy_pass_header指令。
proxy_connect_timeout time;
Default: proxy_connect_timeout 60s;
#定义与代理服务器建立连接的超时。应该注意,此超时通常不会超过75秒。
proxy_read_timeout time;
Default: proxy_read_timeout 60s;

定义从代理服务器读取响应的超时。仅在两个连续的读操作之间设置超时,而不是为整个响应的传输。如果代理服务器在此时间内未传输任何内容,则关闭连接。

proxy_send_timeout time;
Default: proxy_send_timeout 60s;
#设置将请求传输到代理服务器的超时。仅在两个连续的写操作之间设置超时,而不是为整个请求的传输。如果代理服务器在此时间内未收到任何内容,则关闭连接。
proxy_buffer_size size;
Default: proxy_buffer_size 4k|8k;
#设置用于读取从代理服务器接收的响应的第一部分的缓冲区的大小。这部分通常包含一个小的响应头。
proxy_bind address [transparent] | off
#使用可选端口(1.11.2)从指定的本地IP地址发出到代理服务器的传出连接。
proxy_buffering on | off;
Default: proxy_buffering on;
#启用或禁用来自代理服务器的响应缓冲。
proxy_buffers number size;
Default: proxy_buffers 8 4k|8k;
#设置用于从代理服务器读取响应的缓冲区的数量和大小,用于单个连接。默认情况下,缓冲区大小等于一个内存页面。
proxy_busy_buffers_size size;
Default: proxy_busy_buffers_size 8k|16k;
#当启用来自代理服务器的响应缓冲时,限制可能忙于向响应客户端发送响应的缓冲区的总大小,而响应尚未完全读取。同时,其余缓冲区可用于读取响应,如果需要,还可以缓冲部分响应临时文件。默认情况下,size由
proxy_buffer_size和proxy_buffers指令设置的两个缓冲区的大小限制。
proxy_cache zone | off;
Default: proxy_cache off;
#定义用于缓存的共享内存区域。指明要调用的缓存,或关闭缓存机制
proxy_cache_background_update on | off;
Default: proxy_cache_background_update off;
#允许启动后台子请求以更新过期的缓存项,同时将过时的缓存响应返回给客户端。请注意,在更新时必须允许使用陈旧的缓存响应。
proxy_cache_bypass string …;
#定义不从缓存中获取响应的条件。如果字符串参数的至少一个值不为空且不等于“0”,则不会从缓存中获取响应
proxy_cache_convert_head on | off;
Default: proxy_cache_convert_head on;
#启用或禁用将“HEAD”方法转换为“GET”以进行缓存。
proxy_cache_key string;
Default: proxy_cache_key s c h e m e scheme schemeproxy_hostKaTeX parse error: Expected 'EOF', got '#' at position 14: request_uri; #̲定义缓存的键 proxy_ca…fastcgi_script_name;
#fastcgi_param QUERY_STRING KaTeX parse error: Expected 'EOF', got '#' at position 34: …cgi_index name #̲定义fastcgi默认的主页资… fastcgi_script_name变量的值中设置将在以斜杠结尾的URI之后追加的文件名。
fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
#设置缓存的路径和其他参数。
#fastcgi_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;
fastcgi_cache zone | off;
Default: fastcgi_cache off;

定义用于缓存的共享内存区域。可以在多个地方使用相同的区域。

fastcgi_cache_key string;
#定义缓存的键
#fastcgi_cache_key localhost:9000$request_uri;
fastcgi_cache_methods GET | HEAD | POST …;
Default: fastcgi_cache_methods GET HEAD;
#如果此指令中列出了客户端请求方法,则将缓存响应。 “GET”和“HEAD”方法总是添加到列表中,但建议明确指定它们。
fastcgi_cache_min_uses number;
Default: fastcgi_cache_min_uses 1;
#设置缓存响应之前的请求数。
fastcgi_cache_valid [code …] time;
#设置不同响应代码的缓存时间。
#fastcgi_cache_valid 200 302 10m;
#fastcgi_cache_valid 404 1m;
fastcgi_keep_conn on | off;
Default: fastcgi_keep_conn off;
#默认情况下,FastCGI服务器将在发送响应后立即关闭连接。但是,当此伪指令设置为on时,nginx将指示FastCGI服务器保持连接打开。特别是,这对于与FastCGI服务器的keepalive连接起作用是必要的。
fastcgi_cache_background_update on | off;
Default: fastcgi_cache_background_update off;
#允许启动后台子请求以更新过期的缓存项,同时将过时的缓存响应返回给客户端。请注意,在更新时必须允许使用陈旧的缓存响应。
fastcgi_cache_bypass string …;
#定义不从缓存中获取响应的条件。如果字符串参数的至少一个值不为空且不等于“0”,则不会从缓存中获取响应:
#fastcgi_cache_bypass $cookie_nocache a r g n o c a c h e arg_nocache argnocachearg_comment;
#fastcgi_cache_bypass $http_pragma KaTeX parse error: Expected 'EOF', got '#' at position 47: …he_key string; #̲定义缓存的键 #fastcgi…request_uri;
fastcgi_cache_lock on | off;
Default: fastcgi_cache_lock off;
#通过将请求传递给FastCGI服务器,一次只允许一个请求填充根据fastcgi_cache_key指令标识的新缓存元素。同一缓存元素的其他请求将等待响应出现在缓存中或缓存此元素的缓存锁定,直到fastcgi_cache_lock_timeout指令设置的时间。
fastcgi_cache_lock_age time;
Default: fastcgi_cache_lock_age 5s;
#如果传递给FastCGI服务器以填充新缓存元素的最后一个请求在指定时间内没有完成,则可以将另一个请求传递给FastCGI服务器。
fastcgi_cache_lock_timeout time;
Default: fastcgi_cache_lock_timeout 5s;
#设置fastcgi_cache_lock的超时。当时间到期时,请求将被传递给FastCGI服务器,但是,响应将不会被缓存。
fastcgi_cache_max_range_offset number;
#设置字节范围请求的偏移量(以字节为单位)。如果范围超出偏移量,则范围请求将传递给FastCGI服务器,并且不会缓存响应。
fastcgi_cache_max_range_offset number;
#设置字节范围请求的偏移量(以字节为单位)。
fastcgi_cache_min_uses number;
Default: fastcgi_cache_min_uses 1;
#设置缓存响应之前的请求数。
fastcgi_cache_purge string …;

定义将请求视为缓存清除请求的条件。

fastcgi_cache_revalidate on | off;
Default: fastcgi_cache_revalidate off;
#使用带有“If-Modified-Since”和“If-None-Match”标头字段的条件请求启用过期缓存项的重新验证。
fastcgi_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_503 | http_403 | http_404 | http_429 | off …;
Default: fastcgi_cache_use_stale off;
#确定在与FastCGI服务器通信期间发生错误时可以使用过时的缓存响应的情况。该指令的参数与
fastcgi_next_upstream指令的参数匹配。
fastcgi_catch_stderr string;
#设置要在从FastCGI服务器接收的响应的错误流中搜索的字符串。如果找到该字符串,则认为FastCGI服务器返回了无效响应。这允许在nginx中处理应用程序错误
#location /php/ {

fastcgi_pass backend:9000;

fastcgi_catch_stderr “PHP Fatal error”;

fastcgi_next_upstream error timeout invalid_header;

#}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值