nginx配置文件中的 location 配置详解
一:语法介绍
location 是根据URL来进行不同的定位,location可以把网站的不同部分,定位到不同的处理方式上面
location语法:
location [=|~|~*|^~] patt { } //中括号中为修饰符,可以不写任何参数,此时称为一般匹配,也可以写参数
因此,大类型可以分为三种:
location = patt {} [精准匹配]
location patt{} [普通匹配]
location ~ patt{} [正则匹配]
-
=开头表示精确匹配 -
^~开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。 -
~开头表示区分大小写的正则匹配 -
~*开头表示不区分大小写的正则匹配 -
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配 的正则 -
/通用匹配,任何请求都会匹配到。
多个location配置的情况下匹配顺序为:
首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求。

location命中过程:
1.先进性精准匹配,如果命中立即返回结果并结束解析的过程;
2.精准匹配未命中判断普通匹配,如果命中多个会记录下"最长的"命中结果,但不会结束解析;
3.继续判断正则匹配,按照正则匹配设置的规则正则表达式进行匹配,如果有多个正则匹配由上到下进行匹配,一旦匹配成功一个会立即返回结果并结束解析.
ps:普通匹配的前后顺序是无所谓的,因为记录的是最长的结果,而正则匹配是按从上到下匹配的,这个需要注意!!!
server { listen 80; server_name localhost; location =/text.html { #精准匹配,浏览器输入IP地址/text.html,定位到服务器/var/www/html/text.html文件 root /var/www/html; index text.html; } location / { #普通匹配,浏览器输入IP地址,定位到服务器/usr/local/nginx/html/default.html文件 root html; index default.html; } location ~ image { #正则匹配,浏览器输入IP/image..地址会被命中,定位到/var/www/image/index.html root /var/www/image; index index.html; } }
二:其他配置信息介绍
ReWrite语法
last – 基本上都用这个Flag。break – 中止Rewirte,不在继续匹配redirect – 返回临时重定向的HTTP状态302permanent – 返回永久重定向的HTTP状态301
1、下面是可以用来判断的表达式:
-f和!-f用来判断是否存在文件-d和!-d用来判断是否存在目录-e和!-e用来判断是否存在文件或目录-x和!-x用来判断文件是否可执行
2、下面是可以用作判断的全局变量
例: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:D:\nginx/html $request_filename:D:\nginx/html/test1/test2/test.php
Redirect语法
server { listen 80; server_name start.igrow.cn; index index.html index.php; root html; if ($http_host !~ "^star\.igrow\.cn$" { rewrite ^(.*) http://star.igrow.cn$1 redirect; } }
防盗链
location ~* \.(gif|jpg|swf)$ { valid_referers none blocked start.igrow.cn sta.igrow.cn; if ($invalid_referer) { rewrite ^/ http://$host/logo.png; } }
根据文件类型设置过期时间
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ { if (-f $request_filename) { expires 1h; break; } }
禁止访问某个目录
location ~* \.(txt|doc)${ root /data/www/wwwroot/linuxtone/test; deny all; }
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}
一些可用的全局变量
$args
$content_length
$content_type
$document_root
$document_uri
$host
$http_user_agent
$http_cookie
$limit_rate
$request_body_file
$request_method
$remote_addr
$remote_port
$remote_user
$request_filename
$request_uri
$query
浙公网安备 33010602011771号