- nginx高度模块化,但其模块早期不支持DSO机制;1.9.11版本支持动态装载和卸载
- 模块分类:
核心模块:core module
标准模块:
HTTP 模块: ngx_http_*
HTTP Core modules 默认功能
HTTP Optional modules 需编译时指定
Mail 模块 ngx_mail_*
Stream 模块 ngx_stream_*
第三方模块
- 二、ngx_http_core_module模块
- ngx_http_core_module
#与套接字相关的配置
1、server { ... }
#配置一个虚拟主机
server {
listen address[:PORT]|PORT;
server_name SERVER_NAME;
root /PATH/TO/DOCUMENT_ROOT;
}
2、listen PORT|address[:port]|unix:/PATH/TO/SOCKET_FILE
- listen address[:port] [default_server] [ssl] [http2 | spdy(谷歌的)] [backlog=number] [rcvbuf=size] [sndbuf=size]
- default_server
设定为默认虚拟主机
- ssl
限制仅能够通过ssl连接提供服务
- backlog=number
超过并发连接数后,新请求进入后援队列的长度
- rcvbuf=size
接收缓冲区大小
- sndbuf=size
发送缓冲区大小
- 注意:
(1) 基于port;
listen PORT; 指令监听在不同的端口
(2) 基于ip的虚拟主机
listen IP:PORT; IP 地址不同
(3) 基于hostname
server_name fqdn; 指令指向不同的主机名
#实验:配置虚拟主机
#基于FQDN模式的虚拟主机 server { listen 80; server_name www.b.com; root /app/nginx/web2/; } server { listen 80; server_name www.a.com; root /app/nginx/web1/; } [[email protected]]#ss -ntl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 *:80 *:* [[email protected]~]#vim /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 172.18.68.100 www.a.com www.b.com [[email protected]~]#curl www.a.com www.a.com [[email protected]~]#curl www.b.com www.b.com [[email protected]]#ls default.conf vhosts.conf #注意/etc/nginx/conf.d有多个 conf 文件的话,顺序是安装排序的顺序生效的。 #如果需要请设置默认主机 server { listen 80 default_server; server_name www.b.com; root /app/nginx/web2/; } [[email protected]~]#curl 172.18.68.100 www.b.com
3、server_name name ...;
- 虚拟主机的主机名称后可跟多个由空白字符分隔的字符串
- 支持*通配任意长度的任意字符
server_name *.magedu.com www.magedu.*
- 支持~起始的字符做正则表达式模式匹配,性能原因慎用
server_name ~^www\d+\.magedu\.com$
\d 表示 [0-9]
- 匹配优先级机制从高到低:
(1) 首先是字符串精确匹配 如:www.magedu.com
(2) 左侧*通配符 如:*.magedu.com
(3) 右侧*通配符 如:www.magedu.*
(4) 正则表达式 如: ~^.*\.magedu\.com$
(5) default_server
4、tcp_nodelay on | off;
- 在keepalived模式下的连接是否启用TCP_NODELAY选项
- 当为off时,延迟发送,合并多个请求后再发送(节约带宽,但是会影响用户体验)
- 默认On时,不延迟发送
- 可用于:http, server, location
5、sendfile on | off;
- 是否启用sendfile功能,在内核中封装报文直接发送
- 默认Off
6、server_tokens on | off | build | string
- 是否在响应报文的Server首部显示nginx版本
#隐藏版本号 [[email protected]~]#curl -I www.a.com HTTP/1.1 200 OK Server: nginx/1.12.2 #暴露了版本号 Date: Wed, 07 Mar 2018 19:59:27 GMT Content-Type: text/html Content-Length: 10 Last-Modified: Wed, 07 Mar 2018 19:08:39 GMT Connection: keep-alive ETag: "5aa038b7-a" Accept-Ranges: bytes [[email protected]]#vim vhosts.conf #如果想所有主机都生效,就在 http 内设置 server { listen 80; server_name www.a.com; root /app/nginx/web1/; server_tokens off; } [[email protected]~]#curl -I www.a.com HTTP/1.1 200 OK Server: nginx #如果想nginx也隐藏,就需要购买商业版
#定义路径相关的配置
7、root
- 设置web资源的路径映射;用于指明请求的URL所对应的文档的目录路径,可用于http, server, location, if in location
server {
...
root /data/www/vhost1;
}
- 示例
http://www.magedu.com/images/logo.jpg --> /data/www/vhosts/images/logo.jpg
8、location [ = | ~ | ~* | ^~ ] uri { ... }
- location @name { ... }
- 在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配,而后应用其配置
- 示例:
server {...
server_name www.magedu.com;
location /images/ {
root /data/imgs/;
}
}
http://www.magedu.com/images/logo.jpg --> /data/imgs/images/logo.jpg
[[email protected]]#mkdir /data/413/images -pv [[email protected]]#vim vhosts.conf server { listen 80; server_name www.a.com; root /app/nginx/web1/; server_tokens off; location /images { root /data/413/; } } [[email protected]~]#curl -I www.a.com/images/1.jpg HTTP/1.1 200 OK Server: nginx Date: Wed, 07 Mar 2018 20:13:52 GMT Content-Type: image/jpeg Content-Length: 315191 Last-Modified: Wed, 07 Mar 2018 20:12:50 GMT Connection: keep-alive ETag: "5aa047c2-4cf37" Accept-Ranges: bytes
- =:对URI做精确匹配;
location = / {
...
}
http://www.magedu.com/ 匹配
http://www.magedu.com/index.html 不匹配
- ^~:对URI的最左边部分做匹配检查,不区分字符大小写
- ~:对URI做正则表达式模式匹配,区分字符大小写
- ~*:对URI做正则表达式模式匹配,不区分字符大小写
- 不带符号:匹配起始于此uri的所有的uri
- 匹配优先级从高到低:
=, ^~, ~/~*, 不带符号
- 示例:
- root /vhosts/www/htdocs/
http://www.magedu.com/index.html --> /vhosts/www/htdocs/index.html
- server {
root /vhosts/www/htdocs/
location /admin/ {
root /webapps/app1/data/
}
}
http://www.magedu.com/admin/index.html --> /webapps/app1/data/admin/index.html
location = / { [ configuration A ] } location / { [ configuration B ] } location /documents/ { [ configuration C ] } location ^~ /images/ { [ configuration D ] } location ~* \.(gif|jpg|jpeg)$ { [ configuration E ] } http://www.mgadu.com/ #匹配这个页面的有:A生效,B也匹配,但是优先级低 http://www.magedu.com/index.html #匹配这个页面的有:B http://www.magedu.com/documents/log.jpg #匹配这个页面的有:B、C、E都匹配,但最终生效的是E,因为E的优先级最高 http://www.magedu.com/documents/linux.txt #匹配这个页面的有:B、C都匹配,但是C更精确,所以C生效 http://www.magedu.com/images/log.jpeg #匹配这个页面的有:B、D、E都匹配,但是 ^~的优先级高,所有D生效
9、alias path;
- 路径别名,文档映射的另一种机制;仅能用于location上下文
- path代表的本机
- 示例:
http://www.magedu.com/bbs/index.php
location /bbs/ {
alias /web/forum/;
} --> 等于 /web/forum/index.html
location /bbs/ {
root /web/forum/;
} --> 等于 /web/forum/bbs/index.html
- 注意:location中使用root指令和alias指令的意义不同
(a) root,给定的路径对应于location中的/uri/左侧的/
(b) alias,给定的路径对应于location中的/uri/右侧的/
[[email protected]~]#vim /etc/nginx/conf.d/vhosts.conf server { listen 80; server_name www.a.com; root /app/nginx/web1/; server_tokens off; location /images { alias /data/413/; [[email protected]~]#curl -I www.a.com/images/1.jpg HTTP/1.1 200 OK Server: nginx [[email protected]~]#vim /etc/nginx/conf.d/vhosts.conf root /app/nginx/web2/ server { listen 80; server_name www.b.com; root /app/nginx/web2/; location / { #如果这个location设置后,上面的root /app/nginx/web2/就不再生效 root /data/413; #这的路径,可以是远程NFS的路径 } [[email protected]]#pwd /data/413 [[email protected]]#echo /data/413/ > index.html [[email protected]~]#curl www.b.com /data/413/
10、index file ...;
- 指定默认网页资源
- 注意:ngx_http_index_module模块
- 可以适用于http,server,location
#设置默认页面 [[email protected]]#vim /etc/nginx/conf.d/vhosts.conf server { listen 80; server_name www.a.com; root /app/nginx/web1/; server_tokens off; location /images { alias /data/413/; index 1.jpg; #默认页面设置 } } [[email protected]~]#curl -I www.a.com/images/ HTTP/1.1 200 OK Server: nginx Date: Thu, 08 Mar 2018 04:31:29 GMT Content-Type: image/jpeg
11、error_page code ... [=[response]] uri;
- 模块:ngx_http_core_module
- 定义错误页,以指定的响应状态码进行响应
- 可用位置:http, server, location, if in location
- error_page 404 /404.html
- error_page 404 =200 /404.html
#实验:设置错误页面,防止错误页面被利用(原理,截获错误代码)
[[email protected]~]#curl -I www.b.com/noexist.html HTTP/1.1 404 Not Found Server: nginx #修改配置文件 [[email protected]]#vim /etc/nginx/conf.d/vhosts.conf server { listen 80; server_name www.b.com; error_page 404 /404.html; #错误页面选项 location /404.html { root /data/error_htmls/; #错误页面存放的位置 } root /app/nginx/web2/; location / { root /data/413; } } #测试 [[email protected]]#mkdir /data/error_htmls [[email protected]]#echo /data/error_htmls > /data/error_htmls/404.html [[email protected]~]#curl -I www.b.com/noexist.html #响应报文还是错误的404代码 HTTP/1.1 404 Not Found Server: nginx/1.12.2 Date: Thu, 08 Mar 2018 04:43:36 GMT Content-Type: text/html Content-Length: 18 Connection: keep-alive ETag: "5aa0bf66-12" [[email protected]~]#curl www.b.com/noexist.html #但是页面就直接转到设定好的错误页面 /data/error_htmls #实验,如果发现404,就直接跳转到302 [[email protected]]#echo /data/error_302 > /data/error_htmls/302.html [[email protected]]#vim /etc/nginx/conf.d/vhosts.conf server { listen 80; server_name www.b.com; error_page 404 =302 /302.html; location /302.html { root /data/error_htmls/; } root /app/nginx/web2/; location / { root /data/413; } } [[email protected]~]#curl www.b.com/noexist.html #内容已经跳转 /data/error_302 [[email protected]~]#curl -I www.b.com/noexist.html #错误代码也变更成功 HTTP/1.1 302 Moved Temporarily
12、try_files file ... uri;
- try_files file ... =code;
- 按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误
- 只能在 server,location 中调用
location /images/ {
try_files $uri /images/default.gif; ---> 按照顺序查找,可以写好几个,如果都找不到,就给出设定的页面
}
location / {
try_files $uri $uri/index.html $uri.html =404;
}
[[email protected]]#vim /etc/nginx/conf.d/vhosts.conf server { listen 80; server_name www.a.com; root /app/nginx/web1/; server_tokens off; location /images { try_files $uri /default.jpg; #注意:默认页面位于指定的根下的相对路径 } } [[email protected]]#cp 1.jpg ../default.jpg [[email protected]~]#curl -I www.a.com/images/2.jpg HTTP/1.1 200 OK Server: nginx
#定义客户端请求的相关配置
13、keepalive_timeout timeout [header_timeout];
- 设定保持连接超时时长,0表示禁止长连接,默认为75s
- 注意:默认是开启的
14、keepalive_requests number;
- 在一次长连接上所允许请求的资源的最大数量
- 默认为100
15、keepalive_disable none | browser ...
- 对哪种浏览器禁用长连接
16、send_timeout time;
- 向客户端发送响应报文的超时时长,此处是指两次写操作之间的间隔时长,而非整个响应过程的传输时长
17、client_body_buffer_size size;
- 用于接收每个客户端请求报文的body部分的缓冲区大小;默认为16k;超出此大小时,其将被暂存到磁盘上的由client_body_temp_path指令所定义的位置
- 意思就是,当用户发来请求,请求报文不是单单的get指令,有可能是put等指令,上传的数据也是要放到buff内的,如果超出buff,就放到磁盘上。
- 这个大小的促发值就是这个模块设定的,超出的部分就放到磁盘上,存放的路径就是由下面18的模块来设定
18、client_body_temp_path path [level1 [level2 [level3]]];
- 设定用于存储客户端请求报文的body部分的临时存储路径及子目录结构和数量
- 目录名为16进制的数字;
- client_body_temp_path /var/tmp/client_body 1 2 2
- 1 1级目录占1位16进制,即2^4=16个目录 0-f
- 2 2级目录占2位16进制,即2^8=256个目录 00-ff
- 2 3级目录占2位16进制,即2^8=256个目录 00-ff
#对客户端进行限制的相关配置
19、limit_rate rate;
- 限制响应给客户端的传输速率,单位是bytes/second
- Default:limit_rate 0; 默认值0表示无限制
server {
if ($slow){
set $limit_rate 4k;
}
...
}
[[email protected]]#vim /etc/nginx/conf.d/vhosts.conf server { listen 80; server_name www.a.com; root /data/413/; server_tokens off; keepalive_timeout 600s; #持久连接最长时间,单位为妙 limit_rate 4k; #下载限速,默认单位为字节 } [[email protected]~]#wget www.a.com/bigfile --2018-03-11 20:32:29-- http://www.a.com/bigfile Resolving www.a.com (www.a.com)... 172.18.68.100 Connecting to www.a.com (www.a.com)|172.18.68.100|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 10485760 (10M) [application/octet-stream] 0% [ ] 61,440 4.58KB/s eta 37m 5s
20、limit_except method ... { ... },仅用于location
- 限制客户端使用除了指定的请求方法之外的其它方法
- method:
GET, HEAD, POST, PUT, DELETE
MKCOL, COPY, MOVE, OPTIONS, PROPFIND,
PROPPATCH, LOCK, UNLOCK, PATCH
limit_except GET { #除了的含义,但有GET就包含HEAD
allow 192.168.1.0/24;
deny all;
} #除了GET和HEAD 之外其它方法仅允许192.168.1.0/24网段主机使用
#文件操作优化的配置
21、aio on | off | threads[=pool];
- 是否启用aio功能(就是异步I/O)
22、directio size | off;
- 是否同步(直接)写磁盘,而非写缓存
- 在Linux主机启用O_DIRECT标记,则文件大于等于给定大小时使用
例如directio 4m
23、open_file_cache off(打开的文件缓存是否启用);
- open_file_cache max=N [inactive=time];
- 这个模块的含义就是,当用户去访问网站页面文件的时候,是否事先把页面的元数据提前缓存下来。
- nginx可以缓存以下三种信息:
(1) 文件元数据:文件的描述符、文件大小和最近一次的修改时间
(2) 打开的目录结构
(3) 没有找到的或者没有权限访问的文件的相关信息
- max=N:可缓存的缓存项上限(缓存的总数量,多少条);达到上限后会使用LRU算法实现管理
- inactive=time:缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项,将被删除
24、open_file_cache_errors on | off;
- 是否缓存查找时发生错误的文件一类的信息
- 默认值为off
25、open_file_cache_min_uses number;
- open_file_cache指令的inactive参数指定的时长内,至少被命中此处指定的次数方可被归类为活动项
- 默认值为1
26、open_file_cache_valid time;
- 缓存项有效性的检查频率
- 默认值为60s
- 三、ngx_http_access_module模块
- ngx_http_access_module
#实现基于ip的访问控制功能
1、allow address | CIDR | unix: | all;
2、deny address | CIDR | unix: | all;
- http, server, location, limit_except
- 自上而下检查,一旦匹配,将生效,条件严格的置前
- 示例:
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}
server { listen 80; server_name www.a.com; root /data/413/; server_tokens off; keepalive_timeout 600s; limit_rate 4k; location / { deny 172.18.68.200; #严格的放在前面,上面的优先生效 } } [[email protected]~]#curl www.a.com <html> <head><title>403 Forbidden</title></head>
- 四、ngx_http_auth_basic_module模块
- ngx_http_auth_basic_module
- 实现基于用户的访问控制,使用basic机制进行用户认证
1、auth_basic string | off;
2、auth_basic_user_file file;
- location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.ngxpasswd;
}
- 用户口令文件:
1、明文文本:格式name:password:comment
2、加密文本:由htpasswd命令实现
httpd-tools所提供
#实验:完成Nginx的basic验证
[[email protected]]#vim /etc/nginx/conf.d/vhosts.conf server { listen 80; server_name www.a.com; root /data/413/; server_tokens off; keepalive_timeout 600s; limit_rate 4k; location /admin/ { auth_basic "Admin Area"; #登陆提示信息 auth_basic_user_file /etc/nginx/.ngxpasswd; allow 172.18.68.100; deny all; } } [[email protected]]#mkdir admin [[email protected]]#echo /data/413/admin > admin/index.html [[email protected]]#htpasswd -cm /etc/nginx/.ngxpasswd ngx1 New password: Re-type new password: Adding password for user ngx1 [[email protected]]#cat /etc/nginx/.ngxpasswd ngx1:$apr1$AS9xihbb$Ri22pMx.kgRRgMrz5a6.00 [[email protected]]#chmod 600 /etc/nginx/.ngxpasswd #注意要注意这个文件的安全 [[email protected]]#ll /etc/nginx/.ngxpasswd -rw------- 1 root root 86 Mar 8 14:27 /etc/nginx/.ngxpasswd [[email protected]]#htpasswd -m /etc/nginx/.ngxpasswd ngx2 New password: Re-type new password: Adding password for user ngx2 [[email protected]]#cat /etc/nginx/.ngxpasswd ngx1:$apr1$AS9xihbb$Ri22pMx.kgRRgMrz5a6.00 ngx2:$apr1$UyK2uWC4$yvxzBfCyE1Y5YRLYylSGZ0 [[email protected]~]#curl www.b.com/admin/ /data/413/admin [[email protected]~]#curl www.a.com/admin/ <head><title>401 Authorization Required</title></head> #401,验证代码 [[email protected]~]#links www.a.com/admin/ /data/413/admin
- 五、ngx_http_stub_status_module模块
- ngx_http_stub_status_module
- 用于输出nginx的基本状态信息
- 适用于 server,location
- 输出信息示例:
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
上面三个数字分别对应accepts,handled,requests三个值
Reading: 6 Writing: 179 Waiting: 106
- Active connections:当前状态,活动状态的连接数
- accepts:统计总值,已经接受的客户端请求的总数
- handled:统计总值,已经处理完成的客户端请求的总数
- requests:统计总值,客户端发来的总的请求数
- Reading:当前状态,正在读取客户端请求报文首部的连接的连接数
- Writing:当前状态,正在向客户端发送响应报文过程中的连接数
- Waiting:当前状态,正在等待客户端发出请求的空闲连接数
stub_status;
- 示例:
location /status {
stub_status;
allow 172.16.0.0/16;
deny all;
}
#实验:启用status页面
server { listen 80; server_name www.a.com; root /data/413/; server_tokens off; keepalive_timeout 600s; limit_rate 4k; location /status { stub_status; allow 172.18.68.100; deny all; } } [[email protected]~]#curl www.a.com/status Active connections: 1 #服务器接收 处理 请求 server accepts handled requests --->#表示总共的值 1 1 1 Reading: 0 Writing: 1 Waiting: 0 --->#正在处理的 读 写 等待
- 六、ngx_http_log_module模块
- ngx_http_log_module
- 指定日志格式记录请求
- 用法:先定义格式,在调用定义的模式
1、log_format name string ...;
- string可以使用nginx核心模块及其它模块内嵌的变量
- 定义日志的格式
- 注意适用位置:只能使用在 http 设置中
2、access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
- access_log off;
- 访问日志文件路径,格式及相关的缓冲的配置
buffer=size
flush=time
- 适用位置:http server location
- 示例
log_format compression '$remote_addr - $remote_user [$time_local](本地时间) "$request"(请求的url) '
'$status(响应状态码) $body_bytes_sent "$http_referer"(跳转信息) '
'"$http_user_agent"(用户代理,用户浏览器名称) "$gzip_ratio"(压缩比) "$http_x_forwarded_for"';
注意:调用的变量,如果是编译的,编译的时候要注意加载模块
access_log /spool/logs/nginx-access.log compression buffer=32k;
3、open_log_file_cache(日志缓存) max=N [inactive=time] [min_uses=N] [valid=time];
- open_log_file_cache off;
- 缓存各日志文件相关的元数据信息
- max:缓存的最大文件描述符数量
- min_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项
- inactive:非活动时长
- valid:验证缓存中各缓存项是否为活动项的时间间隔
- 七、ngx_http_gzip_module模块
- ngx_http_gzip_module
- 用gzip方法压缩响应数据,节约带宽
1、gzip on | off;
- 启用或禁用gzip压缩
- 默认是不压缩的
- 适用环境 http, server, location, if in location
2、gzip_comp_level level;
- 压缩比由低到高:1 到 9
- 默认:1
- 适用环境 http, server, location,
3、gzip_disable regex ...;
- 匹配到客户端浏览器不执行压缩
4、gzip_min_length length;
- 启用压缩功能的响应报文大小阈值
5、gzip_http_version 1.0 | 1.1;
- 设定启用压缩功能时,协议的最小版本
- 默认:1.1
6、gzip_buffers number size;
- 支持实现压缩功能时缓冲区数量及每个缓存区的大小
- 默认:32 4k 或 16 8k
- 适用环境 http, server, location,
7、gzip_types mime-type ...;
- 指明仅对哪些类型的资源执行压缩操作;即压缩过滤器
- 默认包含有text/html,不用显示指定,否则出错
8、gzip_vary on | off;
- 如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”
9、gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
- nginx对于代理服务器请求的响应报文,在何种条件下启用压缩功能
- off:对被代理的请求不启用压缩
- expired,no-cache, no-store,private:对代理服务器请求的响应报文首部Cache-Control值任何一个,启用压缩功能
- 示例:
gzip on;
gzip_comp_level 6;
gzip_min_length 64;
gzip_proxied any;
gzip_types text/xml text/css application/javascript;
#实验:实现压缩
[[email protected]]#ll index.html -rw-r--r-- 1 root root 10485760 Mar 8 13:56 index.html [[email protected]~]#curl -I www.a.com HTTP/1.1 200 OK Server: nginx Date: Thu, 08 Mar 2018 07:14:01 GMT Content-Type: text/html Content-Length: 10485760 #与上面的index.html的文件一致 Last-Modified: Thu, 08 Mar 2018 05:56:49 GMT Connection: keep-alive ETag: "5aa0d0a1-a00000" Accept-Ranges: bytes server { listen 80; server_name www.a.com; root /data/413/; server_tokens off; keepalive_timeout 600s; limit_rate 4k; gzip on; gzip_comp_level 9; gzip_min_length 64; gzip_types text/plain; } [[email protected]~]#curl -I --compressed www.a.com HTTP/1.1 200 OK Server: nginx Date: THU, 08 Mar 2018 07:31:14 GMT Content-Type: text/html Last-Modified: Thu, 08 Mar 2018 05:56:49 GMT Connection: keep-alive ETag: W/"5aa0d0a1-a00000" Content-Encoding: gzip [[email protected]]#cat /var/log/nginx/access.log 172.18.68.200 - - [08/Mar/2018:15:32:51 +0800] "GET / HTTP/1.1" 200 10249 "-" "curl/7.29.0" "-"
- 八、ngx_http_ssl_module模块
- ngx_http_ssl_module
- 适用于 http server
- Nginx可以做到不同的主机,是否加密,也可以用不同的证书来进行加密
1、ssl on | off;
- 为指定虚拟机启用HTTPS protocol, 建议用listen指令代替
2、ssl_certificate file;
- 当前虚拟主机使用PEM格式的证书文件
3、ssl_certificate_key file;
- 当前虚拟主机上与其证书匹配的私钥文件
4、ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
- 支持ssl协议版本,默认为后三个
5、ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
- builtin[:size]:使用OpenSSL内建缓存,为每worker进程私有
- [shared:name:size]:在各worker之间使用一个共享的缓存
6、ssl_session_timeout time;
- 客户端连接可以复用ssl session cache中缓存的ssl参数的有效时长,默认5m
- 示例:
server {
listen 443 ssl; #要注意i这个ssl,一定要写上,不然就是监听不加密的443端口了
server_name www.magedu.com;
root /vhosts/ssl/htdocs;
ssl on;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
}
#安装 mod_ssl 模块 [[email protected]~]#yum install mod_ssl #安装完成模块后,就会自动生产一个私钥文件和证书 [[email protected]~]#ll /etc/pki/tls/certs/localhost.crt -rw------- 1 root root 1395 Mar 8 17:35 /etc/pki/tls/certs/localhost.crt [[email protected]~]#ll /etc/pki/tls/private/localhost.key -rw------- 1 root root 1675 Mar 8 17:35 /etc/pki/tls/private/localhost.key #自签名 [[email protected]]#pwd /etc/pki/tls/certs #修改Makefile文件,删除生成私钥的加密选项 [[email protected]]#vim Makefile %.key: umask 77 ; /usr/bin/openssl genrsa $(KEYLEN) > [email protected] #生成私钥文件,并且自签名 [[email protected]]#make https.crt umask 77 ; /usr/bin/openssl genrsa > https.key Generating RSA private key, 1024 bit long modulus ......++++++ ...........++++++ e is 65537 (0x10001) umask 77 ; /usr/bin/openssl req -utf8 -new -key https.key -x509 -days 365 -out https.crt -set_serial 0 You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:CN State or Province Name (full name) []:beijing Locality Name (eg, city) [Default City]:beijing Organization Name (eg, company) [Default Company Ltd]:magedu Organizational Unit Name (eg, section) []:opt Common Name (eg, your name or your server's hostname) []:www.a.com Email Address []: #把私钥和自签名正式放到固定的目录下 [[email protected]]#mkdir ssl [[email protected]]#mv https.* /etc/nginx/conf.d/ [[email protected]]#cd /etc/nginx/conf.d/ [[email protected]]#mv https.* ssl/ server { listen 443 ssl; server_name www.a.com; root /data/413/; server_tokens off; keepalive_timeout 600s; limit_rate 4k; ssl on; ssl_certificate /etc/nginx/conf.d/ssl/https.crt; ssl_certificate_key /etc/nginx/conf.d/ssl/https.key; ssl_session_cache shared:sslcache:20m; ssl_session_timeout 10m; gzip on; gzip_comp_level 9; gzip_min_length 64; gzip_types image/jpeg; } #测试 [[email protected]]#echo https:443 > /data/413/index.html [[email protected]]#ss -ntl State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 *:80 *:* LISTEN 0 128 *:443 *:* [[email protected]~]#curl -k https://www.a.com https:443 #一个ip不同的主机可以绑定不同的证书,但是必须启用一个设置,如果是编译的模式 [[email protected]]#nginx -V nginx version: nginx/1.12.2 built by gcc 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC) built with OpenSSL 1.0.1e-fips 11 Feb 2013 TLS SNI support enabled #这个必须有,不然无法实现 #实现两个网站使用不同的证书文件 [[email protected]]#vim Makefile %.key: umask 77 ; /usr/bin/openssl genrsa -aes128 2048 > [email protected] [[email protected]]#make https_b.crt umask 77 ; /usr/bin/openssl genrsa -aes128 2048 > https_b.key Generating RSA private key, 2048 bit long modulus ............................................................................+++ .....+++ e is 65537 (0x10001) Enter pass phrase: Verifying - Enter pass phrase: #因为私钥是加密的,所以自签名的时候需要输入密码 umask 77 ; /usr/bin/openssl req -utf8 -new -key https_b.key -x509 -days 365 -out https_b.crt -set_serial 0 Enter pass phrase for https_b.key: You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:CN State or Province Name (full name) []:beijing Locality Name (eg, city) [Default City]:beijing Organization Name (eg, company) [Default Company Ltd]:magedu Organizational Unit Name (eg, section) []:pot Common Name (eg, your name or your server's hostname) []:www.b.com Email Address []: [[email protected]]#mv https_b.* /etc/nginx/conf.d/ssl/ [[email protected]]#cd - /etc/nginx/conf.d #修改第二个加密主机的配置文件 [[email protected]]#vim vhosts.conf server { listen 443 ssl; server_name www.b.com; error_page 404 =302 /302.html; root /app/nginx/web2/; ssl on; ssl_certificate /etc/nginx/conf.d/ssl/https_b.crt; ssl_certificate_key /etc/nginx/conf.d/ssl/https_b.key; ssl_session_cache shared:sslcache:20m; ssl_session_timeout 10m; } [[email protected]]#echo https-b > /app/nginx/web2/index.html #测试,因为密码是加密的,所以重启服务都需要输入私钥1密码 [[email protected]~]#nginx Enter PEM pass phrase: [[email protected]~]#curl -k https://www.b.com https-b #去除私钥密码 [[email protected]]#openssl rsa -in ssl/https_b.key -out ssl/https_b.key Enter pass phrase for ssl/https_b.key: writing RSA key
- 九、ngx_http_rewrite_module模块
- ngx_http_rewrite_module
- The ngx_http_rewrite_module module is used to change request URI using PCRE regular expressions, return redirects, and conditionally select configurations.
- 将用户请求的URI基于PCRE regex所描述的模式进行检查,而后完成重定向替换(相当于跳转)
- 示例:
http://www.magedu.com/hn --> http://www.magedu.com/henan
http://www.magedu.com --> https://www.magedu.com/
1、rewrite regex replacement [flag]
- 将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为replacement指定的新的URI
- 注意:如果在同一级配置块中存在多个rewrite规则,那么会自上而下逐个检查;被某条件规则替换完成后,会重新一轮的替换检查
- 隐含有循环机制,但不超过10次;如果超过,提示500响应码,[flag]所表示的标志位用于控制此循环机制
- 如果replacement是以http://或https://开头,则替换结果会直接以重向返回给客户端
- 301:永久重定向
- [flag]
last:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环,不建议在lation中使用
break:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环,建议在location中使用
redirect:临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;不能以http://或https://开头,使用相对路径,状态码:302
permanent:重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求,状态码:301
2、return
- return code [text];
- return code URL;
- return URL;
- 停止处理,并返回给客户端指定的响应码
3、rewrite_log on | off;
- 是否开启重写日志, 发送至error_log(notice level)
4、set $variable value;
- 用户自定义变量
- 注意:变量定义和调用都要以$开头
5、if (condition) { ... }
- 引入新的上下文,条件满足时,执行配置块中的配置指令
- server, location,condition:
- 比较操作符:
== 相同
!= 不同
~:模式匹配,区分字符大小写
~*:模式匹配,不区分字符大小写
!~:模式不匹配,区分字符大小写
!~*:模式不匹配,不区分字符大小写
- 文件及目录存在性判断:
-e, !-e 存在(包括文件,目录,软链接)
-f, !-f 文件
-d, !-d 目录
-x, !-x 执行
#实现bbs 跳转到 forum 页面 [[email protected]]#vim vhosts.conf server { listen 80; server_name www.a.com; root /data/413/; location /bbs/ { rewrite ^/bbs(.*) /forum$1 last; } } [[email protected]]#mkdir /data/413/forum [[email protected]]#echo forum > /data/413/forum/index.html [[email protected]~]#curl www.a.com/bbs forum [[email protected]~]#curl -I www.a.com/bbs HTTP/1.1 200 OK #实现redirect [[email protected]]#vim vhosts.conf server { listen 80; server_name www.a.com; root /data/413/; location /bbs/ { rewrite ^/bbs(.*) /forum$1 redirect; } } [[email protected]~]#curl www.a.com/bbs/ -L #curl 不支持自己跳转,需要加-L选项 forum [[email protected]~]#curl www.a.com/bbs/ <html> <head><title>302 Found</title></head> #实现永久重定向 permanent [[email protected]]#vim vhosts.conf server { listen 80; server_name www.a.com; root /data/413/; location /bbs/ { rewrite ^/bbs(.*) /forum$1 permanent; } } [[email protected]~]#curl -I www.a.com/bbs/ HTTP/1.1 301 Moved Permanently [[email protected]~]#curl www.a.com/bbs/ -L forum #实现http跳转到https server { listen 80; server_name www.a.com; root /data/413/; location / { rewrite / https://www.a.com/ permanent; } } server { listen 443 ssl; server_name www.a.com; root /data/413/; ssl on; ssl_certificate /etc/nginx/conf.d/ssl/https.crt; ssl_certificate_key /etc/nginx/conf.d/ssl/https.key; ssl_session_cache shared:sslcache:20m; ssl_session_timeout 10m; } [[email protected]]#echo https://www.a.com > /data/413/index.html [[email protected]~]#curl -k -L http://www.a.com https://www.a.com [[email protected]~]#curl -I http://www.a.com HTTP/1.1 301 Moved Permanently Server: nginx/1.12.2 Date: Thu, 08 Mar 2018 11:23:58 GMT Content-Type: text/html Content-Length: 185 Connection: keep-alive Location: https://www.a.com/ #使用if实现 http 跳转 https [[email protected]]#vim vhosts.conf server { listen 80; listen 443 ssl; server_name www.a.com; root /data/413/; #ssl on; ssl_certificate /etc/nginx/conf.d/ssl/https.crt; ssl_certificate_key /etc/nginx/conf.d/ssl/https.key; location / { if ( $scheme = "http" ) { rewrite / https://www.a.com/ permanent; } } } [[email protected]~]#curl www.a.com <html> <head><title>301 Moved Permanently</title></head> <body bgcolor="white"> <center><h1>301 Moved Permanently</h1></center> <hr><center>nginx/1.12.2</center> </body> </html> [[email protected]~]#curl -L -k https://www.a.com https://www.a.com #实现客户访问的url带有admin字符串的,直接拒绝访问 [[email protected]]#vim vhosts.conf server { listen 80; server_name www.a.com; root /data/413/; server_tokens off; location / { if ( $uri ~* .*admin.* ) { return 403 "Forbidden!"; } } } [[email protected]~]#curl http://www.a.com/admin Forbidden! [[email protected]~]#curl -I http://www.a.com/admin HTTP/1.1 403 Forbidden
- 十、ngx_http_referer_module模块
- ngx_http_referer_module
- 用来阻止Referer首部无有效值的请求访问,可防止盗链
1、valid_referers none|blocked|server_names|string ...;
- 定义referer首部的合法可用值,不能匹配的将是非法值
- none:请求报文首部没有referer首部
- blocked:请求报文有referer首部,但无有效值
- server_names:参数,其可以有值作为主机名或主机名模式
- arbitrary_string:任意字符串,但可使用*作通配符
- regular expression:被指定的正则表达式模式匹配到的字符串,要使用~开头,例如: ~.*\.magedu\.com
- 示例:
valid_referers none block server_names *.magedu.com *.mageedu.com magedu.* mageedu.* ~\.magedu\.;
if ($invalid_referer) {
return 403 http://www.magedu.com;
}
#实验:实现防盗链 #设置盗链 [[email protected]]#vim link.html <img src="http://www.b.com/default.jpg"/> [[email protected]]#vim vhosts.conf server { listen 80; server_name www.a.com; root /data/413/; } server { listen 80; server_name www.b.com; root /app/website/; } [[email protected]]#cp default.jpg /app/website/ [[email protected]]#cat /var/log/nginx/access.log 172.18.0.1 - - [09/Mar/2018:00:00:54 +0800] "GET /default.jpg HTTP/1.1" 200 315191 "http://www.a.com/link.html" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" "-" #拒绝盗链设置 server { listen 80; server_name www.b.com; root /app/website/; valid_referers none block server_names *.b.com b.* ~\.baidu\.; #先定义合法的地址 if ($invalid_referer) { return 403 ; } }
原文地址:http://blog.51cto.com/exia00linux/2086259