include /etc/nginx/conf.d/*.conf #可定义server的扩展配置文件,一般配置server在此扩展,便于管理,建议关闭SELinux
server中常用模块 server{ listen80; root /app/test; index 404.html; 是针对上面root定义的网页根目录为/app/test时,默认主页面文件为404.html 如果 location 中定义根目录下子目录wpuser时,访问www.a.com/wpuser时,默认网页文件依然是404.html
访问日志格式 access_log /var/log/nginx/www.a.com.access.log main; 注:日志格式由http段中log_formart定义
try_files try_files $uri /vhost/404.html =404; #访问主站点默认页面($uri)如果不存在就找/app/test/vhost/404.html 不存在返回的是404,如果不加上面=404会返回200 $uri等同于当前request中的URI,可不同于初始值,例如内部重定向时或使用index 例子: 1 2 3 4 | location ~* ^/document/(.*)${ root /www/htdocs try_files $uri /docu/$1 /temp.html } |
表示依次匹配: http://www.magedu.com/documents/a.html http://www.magedu.com/docu/a.html http://www.magedu.com/temp.html
error_page 当对于某个请求发回错误时,如果匹配上了error_page指令中设定的code, 则从定向至新的新URI中;错误页面重定向 error_page 404 /404.html 当你访问一个不存在的页面的时候,实际上访问的是404.html文件 需要定义404.html文件路径配合location定义 location /404.html { root /app/wesite; } Syntax: | error_page code ... [=[response]] uri; | Default: | — | Context: | http, server, location, if in location |
alias 指定路径别名,只能用于location中,从最后一个/开始匹配 location /images{ alias /app/test/vhost; #如果使用/images/和/vhost将报错 } index 定义默认主页,可以跟多个值,自左向右匹配 location / {
index index.$geo.html index.html;
} Syntax: | index file ...; | Default: | index index.html; | Context: | http, server, location |
location /image/ { 用户认证访问控制 auth_basic "closed site";
auth_basic_user_file/conf/htpasswd; auth_basic用户认证展示内容,随意填写,如果要关闭用户认证,则auth_basic off即可。auth_basic_user_file表示用户密码存储,使用Apache发行包中的htpasswd命令来创建conf/htpasswd文件,而htpasswd命令需要安装httpd才可以使用,所以: # yum -y install httpd # htpasswd -b -c -m /conf/htpasswd usernamepassword username是你的用户名,password是你的密码 } limit_eccept 客户端请求限制 limit_ecceptDELETE { #limit只能放入location中,只允许172.18.243.43主机执行除了delete外其它指令如get,put 主站点目录下/image/中的文件 ip访问控制 allow 172.18.343.43; 逐条匹配,范围小放前面,同iptables deny all; }
目录下面的文件列表显示,常用于建立下载点 当根访问目录下默认index主页面不存在时,主要用到autoindex这个参数来开启显示目录,其配置如下: 代码如下: location/back/ { root/app/test; //指定实际目录绝对路径; autoindexon; //开启目录浏览功能; autoindex_exact_sizeoff; //关闭详细文件大小统计,让文件大小显示MB,GB单位,默认为b; autoindex_localtimeon; //开启以服务器本地时区显示文件修改日期! allow all; } 如上配置后,用IE访问该服务器的根目录下back目录,就会显示出 back目录下的所有文件列表,Nginx目录浏览效果图: curlwww.a.com/back/ curl测试须 /back/不然会认为是文件 https://s1.51cto.com/oss/201710/30/6be3f2ff5a913e58ac046855b20d89ec.jpg-wh_500x0-wm_3-wmp_4-s_1530345684.jpg
为了备忘,最后将apache下的配置方法也记录一下!实现效果和上面一样! 复制代码 代码如下: Alias/ ”/data/www/file” < Directory ”/data/www/file” > OptionsIndexes //开启目录列表索引模式 Order allow,deny IndexOptions NameWidth = 25 Charset = UTF-8 //设定文件名显示长度,文字字符编码 Allow from all </ Directory >
状态查询 stub_status可以监控Nginx的一些状态信息,默认安装可能没有这个模 在默认主机里面加上location或者你希望能访问到的主机里面。 location /ngx_status { stub_status on; access_log off; #allow 127.0.0.1; #deny all; } } 重新加载nginx,打开status页面 Active connections:11921 server acceptshandled requests 1198911989 11991 Reading: 0 Writing: 7Waiting: 42 注: active connections –活跃的连接数量 server acceptshandled requests — 总共处理了11989个连接 , 成功创建11989次握手, 总共处理了11991个请求 reading — 读取客户端的连接数. writing — 响应数据到客户端的数量 waiting — 开启keep-alive 的情况下,这个值等于 active – (reading+writing), 意思就是 Nginx已经处理完正在等候下一次请求指令的驻留连接. url rewrite地址重写 如果相对域名或参数字符串起作用,可以使用全局变量匹配,也可以使用proxy_pass反向代理。 表明看rewrite和location功能有点像,都能实现跳转,主要区别在于rewrite是在同一域名内更改获取资源的路径,而location是对一类路径做控制访问或反向代理,可以proxy_pass到其他机器。很多情况下rewrite也会写在location里,它们的执行顺序是: - 执行server块的rewrite指令
- 执行location匹配
- 执行选定的location中的rewrite指令
如果其中某步URI被重写,则重新循环执行1-3,直到找到真实存在的文件;循环超过10次,则返回500Internal Server Error错误。 flag标志位 - last : 相当于Apache的[L]标记,表示完成rewrite
- break : 停止执行当前虚拟主机的后续rewrite指令集
- redirect : 返回302临时重定向,地址栏会显示跳转后的地址
- permanent : 返回301永久重定向,地址栏会显示跳转后的地址
因为301和302不能简单的只返回状态码,还必须有重定向的URL,这就是return指令无法返回301,302的原因了。这里last 和 break 区别有点难以理解: - last一般写在server和if中,而break一般使用在location中
- last不终止重写后的url匹配,即新的url会再从server走一遍匹配流程,而break终止重写后的匹配
- break和last都能组织继续执行后面的rewrite指令
if指令与全局变量 if判断指令 语法为if(condition){...},对给定的条件condition进行判断。如果为真,大括号内的rewrite指令将被执行,if条件(conditon)可以是如下任何内容: - 当表达式只是一个变量时,如果值为空或任何以0开头的字符串都会当做false
- 直接比较变量和内容时,使用=或!=
- ~正则表达式匹配,~*不区分大小写的匹配,!~区分大小写的不匹配
-f和!-f用来判断是否存在文件 -d和!-d用来判断是否存在目录 -e和!-e用来判断是否存在文件或目录 -x和!-x用来判断文件是否可执行 例如: if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /msie/$1 break;
} //如果UA包含"MSIE",rewrite请求到/msid/目录下
if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
set $id $1;
} //如果cookie匹配正则,设置变量$id等于正则引用部分
if ($request_method = POST) {
return 405;
} //如果提交方法为POST,则返回状态405(Method notallowed)。return不能返回301,302
if ($slow) {
limit_rate 10k;
} //限速,$slow可以通过 set 指令设置
//如果请求的文件名不存在,则反向代理到localhost。这里的break也是停止rewrite检查
//如果querystring中包含"post=140",永久重定向到example.com
location / { if ($request_method == “PUT”) { }
if ($request_uri ~ "\.(jpg|gif|jpeg|png)$") { proxy_pass http://imageservers; break; } }
全局变量 下面是可以用作if判断的全局变量 - $args : #这个变量等于请求行中的参数,同$query_string
- $content_length : 请求头中的Content-length字段。
- $content_type : 请求头中的Content-Type字段。
- $document_root : 当前请求在root指令中指定的值。
- $host : 请求主机头字段,否则为服务器名称。
- $http_user_agent : 客户端agent信息
- $http_cookie : 客户端cookie信息
- $limit_rate : 这个变量可以限制连接速率。
- $request_method : 客户端请求的动作,通常为GET或POST。
- $remote_addr : 客户端的IP地址。
- $remote_port : 客户端的端口。
- $remote_user : 已经经过Auth Basic Module验证的用户名。
- $request_filename : 当前请求的文件路径,由root或alias指令与URI请求生成。
- $scheme : HTTP方法(如http,https)。
- $server_protocol : 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。
- $server_addr : 服务器地址,在完成一次系统调用后可以确定这个值。
- $server_name : 服务器名称。
- $server_port : 请求到达服务器的端口号。
- $request_uri : 包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”。
- $uri : 不带请求参数的当前URI,$uri不包含主机名,如”/foo/bar.html”。
- $document_uri : 与$uri相同。
例:http://localhost:88/test1/test2/test.php $host:localhost $server_port:88 $request_uri:http://localhost:88/test1/test2/test.php $document_uri:/test1/test2/test.php $document_root:/var/www/html $request_filename:/var/www/html/test1/test2/test.php 常用正则 - . : 匹配除换行符以外的任意字符
- ? : 重复0次或1次
- + : 重复1次或更多次
- * : 重复0次或更多次
- \d :匹配数字
- ^ : 匹配字符串的开始
- $ : 匹配字符串的介绍
- {n} : 重复n次
- {n,} : 重复n次或更多次
- [c] : 匹配单个字符c
- [a-z] : 匹配a-z小写字母的任意一个
小括号()之间匹配的内容,可以在后面通过$1来引用,$2表示的是前面第二个()里的内容。正则里面容易让人困惑的是\转义特殊字符。 rewrite实例 例1: http {
# 定义image日志格式
log_format imagelog '[$time_local] '$image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status;
# 开启重写日志
rewrite_log on; server {
root /home/www; location /{
# 重写规则信息
error_loglogs/rewrite.log notice;
# 注意这里要用‘’单引号引起来,避免{}
rewrite'^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$'/data?file=$3.$4;
#注意不能在上面这条规则后面加上“last”参数,否则下面的set指令不会执行
set $image_file$3;
set $image_type$4;
} location /data{
#指定针对图片的日志格式,来分析图片类型和大小
access_loglogs/images.log mian;
root/data/images;
#应用前面定义的变量。判断首先文件在不在,不在再判断目录在不在,如果还不在就跳转到最后一个url里
try_files /$arg_file/image404.html;
}
location = /image404.html{
# 图片不存在返回特定的信息字符串, return 404 "image notfound\n";
} location /admin{
return 302http://www.baidu.com/; ---表示访问/admin目录时就跳转至百度
return 403 'disallow'; ---表示当访问admin目录时就放回一个字符串disallow } 对形如/images/ef/uh7b3/test.png的请求,重写到/data?file=test.png,于是匹配到location/data,先看/data/images/test.png文件存不存在,如果存在则正常响应,如果不存在则重写tryfiles到新的image404location,直接返回404状态码。 例2: rewrite^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$/resizer/$1.$4?width=$2&height=$3? last; 对形如/images/bla_500x400.jpg的文件请求,重写到/resizer/bla.jpg?width=500&height=400地址,并会继续尝试匹配location。 实例: 准备相应的文件:
| [iyunv@Node7 b.org]# mkdir images [iyunv@Node7 b.org]# cd images [iyunv@Node7 images]# ls 1.jpg |
修改配置:
| server { listen 80 default_server; root /www/b.org/; location /admin { auth_basic "admin area"; auth_basic_user_file /etc/nginx/.htpasswd; }
location /download/ { rewrite ^/download/(.*\.(jpg|gif|jpeg|png))$ /images/$1 break; } } |
测试
可以看到访问的是url是/download/1.jpg,(download这个目录下是没有图片的)被重写至/images/1.jpg,url重写就和路径别名的功能想相似
防盗链 1、定义合规引用 valid_referers none |block|server_names|string ... none:“-”,空,通过浏览器直接访问 blocked:请求报文中有referers字段但被清空 such values are strings thatdo not start with “http://” or “https://”; server_names: the “Referer” request header fieldcontains one of the server names; 请求报文中"Referer"字段包含以下服务器名称;
2、判断不合规的引用 ngx_http_referer_module引入了$invalid_referer变量,$valid_referer是一个布尔值,表示不被valid_referer匹配到都是不合规的引用$invalid_referer if ($invaild_referer) { rewrite ^/.*$ http://www.a.com/403.html } 实例:
| server { listen 80 default_server; root /www/b.org/; location /admin { auth_basic "admin area"; auth_basic_user_file /etc/nginx/.htpasswd; }
location /download/ { # 此时这个location就失效了 rewrite ^/download/(.*\.(jpg|gif|jpeg|png))$ /images/$1 break; } location ~* \.(jpg|png|gif|jgeg)$ { root /www/b.org/; valid_referers none blocked server_names www.b.org *.b.org; #定义一个合法的跳转,也就是允许那些引用; if ($invalid_referer) #return 403; # 使用return和rewrite都可以 } } } |
| [iyunv@Node7 nginx]# cat /www/a.com/index.html aaa.com <img src="http://www.b.org/images/1.jpg"> |
缓存设置 nginx做为反向代理时,能够将来自upstream的响应缓存至本地磁盘(也可以缓存在缓存服务器中,如memcached),并在后续的客户端请求同样内容时直接从本地构造响应报文。 proxy_cache_methods GET |HEAD | POST ...;
对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存 proxy_cache_valid 用于为不同的响应码设定不同时长的有效缓存时长 proxy_cache_use_staleerror | timeout | invalid_header| updating | http_500 | http_502 | http_503 |http_504 | http_403 | http_404 | off...
在被代理的后端服务器出现哪种情况下,可以真接使用过期的缓存响应客户端 proxy_temp_file_write_size 256k; 设置在写入proxy_temp_path时数据的大小,预防一个工作进程在传递文件时阻塞太长 proxy_temp_path /data0/proxy_temp_dir; proxy_temp_path和proxy_cache_path指定的路径必须在同一分区 proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g; #设置内存缓存空间大小为200MB,1天没有被访问的内容自动清除,硬盘缓存空间大小为30GB。1 =16目录,2=16x16子目录
1、vim/etc/nginx/nginx.conf
proxy_cache_path /var/lib/nginx/tmp/pcache levels=1:2:2keys_zone=proxycache:20m inactive=120s max_size=1g; ---注意只能定义在http,不能定义在server、location,keys_zone=proxycache:20m定义一个缓存空间的名字,也就是内存中的缓存空间,大小是20M,max_size=1g表示保存到磁盘上的最大空间是1g
tcp_nodelay on;
2、vim /etc/nginx/conf.d/vhost.conf
server{
listen 80default_server;
server_name www.a.com;
root /app/website1;
location ~ \.html$ {
proxy_pass http://172.18.21.106;
proxy_cache proxycache; ---调用前面定义的缓存空间
proxy_cache_valid 200 301 302 1h; ---定义每种状态码缓存的时间
proxy_cache_valid any1m;
}
} 反向代理 location /my {
proxy_pass http://my_server/; proxy_set_header Host $host:$server_port; proxy_redirect //my/;
}
location /other {
proxy_pass http://other_server;
proxy_set_header Host$host:$server_port; proxy_redirect //other/;
} 注意以上区别:访问根目录下/my目录反向代理为http://my server/ 访问根目录下/other目录反向代理为http://other server/other/
|