下载安装
#wget https://openresty.org/download/ngx_openresty-1.7.10.1.tar.gz
#tar xf ngx_openresty-1.7.10.1.tar.gz
#cd ngx_openresty-1.7.10.1
#./configure --with-luajit
#make && make install
【location】
=开头表示精确匹配
^~ 开头表示uri以某个常规字符串开头,不是正则匹配
~ 开头表示区分大小写的正则匹配;
~* 开头表示不区分大小写的正则匹配
/ 通用匹配, 如果没有其它匹配,任何请求都会匹配到
匹配优先级
(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)
实例
(1)=/ 和 /
location = / {
[configure A]
}
location / {
[configure B]
}
#curl http://localhost/ 匹配B
分析:本来精确匹配应该为A,但当访问http://localhost/时,默认访问网址为http://localhost/index.html,所以匹配为B
(2)=/index.html 和 /
location = /index.html {
[configure A]
}
location / {
[configure B]
}
#curl http://localhost/ 匹配A
(3)/xixi/ 与 ^~ /xixi/
location /xixi/ {
[configure A]
}
location ^~ /xixi/ {
[configure B]
}
报错:
nginx: [emerg] duplicate location "/xixi/" in /usr/local/openresty/nginx/conf/nginx.conf:58
分析:/xixi/与^~ /xixi/都属于普通字符匹配,属于重复配置
(4)~ /xixi/ 与 ^~ /xixi/
location ~ /xixi/ {
[configure A]
}
location ^~ /xixi/ {
[configure B]
}
#curl http://localhost/xixi/ 匹配B
分析:^~ /xixi/优先级大于正则 ~ /xixi/
#curl http://localhost/xixi
报错:404 Not Found
分析:错误日志显示xixi文件不存在
# tail -n5 logs/error.log
2017/02/17 23:19:52 [error] 9732#0: *118 open() "/usr/local/openresty/nginx/html/haha/xixi" failed (2: No such file or directory), client: 127.0.0.1, server: 192.168.204.131, request: "GET /xixi HTTP/1.1", host: "localhost"
(5)~ /xixi/ 与 /xixi/
location /xixi/ {
[configure A]
}
location ~ /xixi/ {
[configure B]
}
#curl http://localhost/xixi/ 匹配B
(6)分析错误日志
2017/02/18 00:05:38 [error] 9987#0: *207 open() "/usr/local/openresty/nginx/html/haha/favicon.ico" failed (2: No such file or directory), client: 192.168.204.1, server: 192.168.204.131, request: "GET /favicon.ico HTTP/1.1", host: "192.168.204.131"
favicon.ico为URL前的小图标
【add_header】
# 添加头部信息
location = / {
add_header a b always;
}
【if】
Context: location, if in location, limit_except
(1)如果提交方法为GET,则返回状态405 Not Allowed
if ( $request_method = GET)
{
return 405;
}
注意:if后面必须带空格,否则检查配置文件出错
(2)如果请求的文件名不存在,则反向代理到localhost 。
这里的break也是停止rewrite检查
location ~ /xixi {
if (!-f $request_filename)
{
break;
proxy_pass http://127.0.0.1:8000;
}
(3)防盗链(来至www.lemon.com可以访问到当前站点的图片,否则返回404)
location ~* \.(gif|jpg|png|swf|flv)$ {
valid_referers none blocked www.lemon.com;
if ($invalid_referer) {
return 404;
}
【rewrite】
(1)重写http://IP/haha/*.html到http://IP/xixi/*.html
http {
# 开启重写日志
rewrite_log on;
server {
location / {
error_log logs/rewrite.log notice;
rewrite '^/haha/(.*)\.(html)' /xixi/$1.$2;
root html;
index index.html index.htm;
}
}
}
【常用正则】
. : 匹配除换行符以外的任意字符
? : 重复0次或1次
+ : 重复1次或更多次
* : 重复0次或更多次
\d :匹配数字
^ : 匹配字符串的开始
$ : 匹配字符串的介绍
{n} : 重复n次
{n,} : 重复n次或更多次
[c] : 匹配单个字符c
[a-z] : 匹配a-z小写字母的任意一个
小括号()之间匹配的内容,可以在后面通过$1来引用,$2表示的是前面第二个()里的内容。正则里面容易让人困惑的是\转义特殊字符。