颠覆与创新

超态信息插件 Sinfo

不想变成栏目的信息不是好信息

更新时间:2016-05-02
首页 > 建站技术文档 > nginx配置文件中location详解

nginx配置文件中location详解

来源:互联网   作者:东坡网整理   发布日期:2019-04-09 21:16:21   阅读次数:3881

Syntax:	location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default:	—
Context:	server, location

1 、[] 表示可选,可以不要。依据不同的前缀“= ”,“^~ ”,“~ ”,“~* ”和不带任何前缀,表达不同的含义。

2 、查询字符串不在URI范围内。例如:/films.htm?fid=123 的URI 是/films.htm

3、不同前缀,分2大类,正则location 和 普通location。

(1)“~ ”和“~* ”前缀表示正则location , “~ ”区分大小写,“~* ”不区分大小写

(2)其它前缀,包括“=”、“^~ ”和“@ ”,以及无任何前缀的都属于普通location

4、对于一个特定的 HTTP 请求,nginx先匹配普通location 再匹配 正则location

普通location 匹配只是临时结果,nginx 还需要继续检查正则location 。如果正则location匹配成功,临时结果将被覆盖,否则最后结果是之前匹配的临时结果。

5、普通location内部的匹配原则是 最大前缀匹配

例如: location /prefix/mid/ {} 和 location /prefix/ {} ,,对于HTTP 请求/prefix/mid/index.html 会匹配 location /prefix/mid/ {}

6、匹配普通location 后 阻止匹配 正则location 的方法是前面加符号 “^~ ”

^ 表示“非”,~ 表示“正则”,“^~ ”字符意思是:不要继续匹配正则

7、加“= ”可以阻止正则匹配,“= ”表示 严格精确匹配

例子1:先普通location ,再正则location

假设 nginx 的配置如下:

server {
       listen       80;
       server_name  localhost;

       # 普通 location 以“ / ”开始的 URI 请求,所有的请求都能被匹配上
       location / { 
           root   html;
           index  index.html;
           deny all; #拒绝访问
       }
       # 以 .html 结尾的 URI 请求
	   location ~ \.html$ {
           allow all; #允许访问
       }
	   # 精确匹配
	   location /a/1.html {
           allow all;
       }
}

测试和结果:

127.0.0.1/				403 Forbidden	匹配普通location
127.0.0.1/index.html	200 ok			匹配正则location		
127.0.0.1/abc.html		404 Not Found	匹配正则location
127.0.0.1/a/1.html		200 ok			匹配普通location的精确匹配

例2:正则匹配

server {
       listen       80;
       server_name  localhost;
	   # 以 /p/ 开头,.html 结尾的所有 URI 请求
       location ~ ^/p/.*\.html$ {
           deny all;  
       }
	   # .html 结尾的所有 URI 请求
       location ~ \.html$ {
           allow all; 
       }
	   # 以 /a/ 开头,.html 结尾的所有 URI 请求,本设置无效
       location ~ ^/a/.*\.html$ {
           deny all;  
       }
}

测试和结果:

127.0.0.1/c.html	404 Not Found	匹配第二个location
127.0.0.1/p/1.html	403 Forbidden	匹配第一个location
127.0.0.1/a/1.html	404 Not Found	匹配第二个location

例3:“@” 前缀 Named Location

假设配置如下:

server {
       listen       80;
       server_name  localhost;

       location  / {
           root   html;
           index  index.html index.htm;
           allow all;

       }
       # 设置404页面
       error_page 404 = @fallback;
	   # 请求代理到 baidu.com
       location @fallback {
           proxy_pass https://www.baidu.com;
       }
}
相关文档
    暂无相关信息
相关插件
    暂无相关信息
联系我们

技术支持:点击这里给我发消息

其它咨询:点击这里给我发消息

微信号:imDP1037,注明东坡网

ECMS互助QQ群:308293433

©2013-2019 DP1037.COM东坡网,致力于帝国cms插件和二次开发,为帝国cms加油! 备案号:粤ICP备14036885号-2

本页采用东坡网【动态页缓存插件】,当前页面缓存时间 2024-03-28 20:32:26
本次重新生成缓存,总耗时 0.0028247833251953 秒