Location的语法:
location 有”定位”的意思, 根据Uri来进行不同的定位.
在虚拟主机的配置中,是必不可少的,location可以把网站的不同部分,定位到不同的处理方式上.
比如, 碰到.php, 如何调用PHP解释器? --这时就需要location
location 的语法:
location [=|~|~*|^~] patt {
}
中括号可以不写任何参数,此时称为一般匹配
也可以写参数,因此,大类型可以分为3种
1 location = patt {} [精准匹配] 2 location patt{} [一般匹配] 3 location ~ patt{} [正则匹配]
如何发挥作用?
1 首先看有没有精准匹配,如果有,则停止匹配过程. 2 location = patt { 3 config A 4 } 5 如果 $uri == patt,匹配成功,使用configA 6 location = / { 7 root /var/www/html/; 8 index index.htm index.html; 9 } 10 11 location / { 12 root /usr/local/nginx/html; 13 index index.html index.htm; 14 } 15 16 如果访问 http://xxx.com/ 17 定位流程是 18 1: 精准匹配中 ”/” ,得到index页为 index.htm 19 2: 再次访问 /index.htm , 此次内部转跳uri已经是”/index.htm” , 20 根目录为/usr/local/nginx/html 21 3: 最终结果,访问了 /usr/local/nginx/html/index.htm
再来看,正则也来参与.
1 location / { 2 root /usr/local/nginx/html; 3 index index.html index.htm; 4 } 5 6 location ~ image { 7 root /var/www/image; 8 index index.html; 9 } 10 11 如果我们访问 http://xx.com/image/logo.png 12 此时, “/” 与”/image/logo.png” 匹配 13 同时,”image”正则 与”image/logo.png”也能匹配,谁发挥作用? 14 正则表达式的成果将会使用. 15 16 图片真正会访问 /var/www/image/logo.png
我们接下来再看一下下面的这个例子:
1 location / { 2 root /usr/local/nginx/html; 3 index index.html index.htm; 4 } 5 6 location /foo { 7 root /var/www/html; 8 index index.html; 9 } 10 我们访问 http://xxx.com/foo 11 对于uri “/foo”, 两个location的patt,都能匹配他们 12 即 ‘/’能从左前缀匹配 ‘/foo’, ‘/foo’也能左前缀匹配’/foo’, 13 此时, 真正访问 /var/www/html/index.html 14 原因:’/foo’匹配的更长,因此使用之.;
rewrite 重写
下面看一下具体的语法:
重写中用到的指令 if (条件) {} 设定条件,再进行重写 set #设置变量 return #返回状态码 break #跳出rewrite rewrite #重写 If 语法格式 If 空格 (条件) { 重写模式 } 条件又怎么写? 答:3种写法 1: “=”来判断相等, 用于字符串比较 2: “~” 用正则来匹配(此处的正则区分大小写) ~* 不区分大小写的正则 3: -f -d -e来判断是否为文件,为目录,是否存在.
我们看一下下面的具体的例子:
1 if ($remote_addr = 192.168.1.100) { 2 return 403; 3 } 4 5 //判断是不是IE的用户 6 If ($http_user_agent ~ MSIE) { 7 rewrite ^.*$ /ie.htm; 8 break; #(不break会循环重定向) 9 } 10 11 if (!-e $document_root$fastcgi_script_name) { 12 rewrite ^.*$ /404.html 13 break; 14 } 15 注, 此处还要加break,
以 xx.com/dsafsd.html这个不存在页面为例,
我们观察访问日志, 日志中显示的访问路径,依然是GET /dsafsd.html HTTP/1.1
提示: 服务器内部的rewrite和302跳转不一样.
跳转的话URL都变了,变成重新http请求404.html, 而内部rewrite, 上下文没变,
就是说 fastcgi_script_name 仍然是 dsafsd.html,因此 会循环重定向.
set 是设置变量用的, 可以用来达到多条件判断时作标志用.
达到apache下的 rewrite_condition的效果
我们来看一下set变量的一些用法:
1 if ($http_user_agent ~* msie) { 2 set $isie 1; 3 } 4 5 if ($fastcgi_script_name = ie.html) { 6 set $isie 0; 7 } 8 9 if ($isie 1) { 10 rewrite ^.*$ ie.html; 11 }
此时我们不需要加break进行