Nginx location、root、alias、proxy_pass

2,402 阅读3分钟

location匹配

location [=|~|~*|^~] /uri/ {
	...
}

1、=:精确匹配

location = / {
	...
}

必须是 xx.xx.xx.xx:port/ 才会被匹配。
2、^~:不精确匹配

location ^~ /a/ {
	...
}

以a开头的uri,/a/b、/a/c都会被匹配。
3、~:区分大小写匹配
4、~*:不区分大小写匹配

location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
	...
}

不区分后缀大小写匹配图片。
5、!~:区分大小写不匹配
6、!~*:不区分大小写不匹配

root

指定项目的根目录,可以继承serverhttp配置。

location ^~ /test/ {
	root /opt
}

匹配到/test会指定/opt为根目录,访问http://x.x.x.x/test实际上时访问/opt/test目录。
一般root都用来匹配/

location / {
	root /opt/test
}

alias

root不同alias是设置一个别名,不需要这个目录真实存在。

location ^~ /test-alias/ {
    alias /opt/test/alias/;
}

修改配置如上,并在/opt/test目录下新建一个alias/index.html内容为alias test,访问http://118.25.7.84/test-alias/index.html, 可以看到 有一点和root不同的需要注意,alias后边写的路径最后要带/,他是直接把location匹配的关键字后边直接拼到alias的路径后,不会像root一样自动加/
举个例子:

location ^~ /test-alias/ {
    alias /opt/test;
}

以上写法访问http://118.25.7.84/test-alias/index.html真实路径会是opt/testindex.html

关于location匹配路径的/

/opt目录下建test/index.html,里边放一个字符串root test

location ^~ /test/ {
    root   /opt;
}

重启nginx,访问http://118.25.7.84/test/index.html,可以看到 可以成功访问
location修改如下

location ^~ test/ {
    root   /opt;
}

重启后再访问发现404。 看一下日志

2020/12/06 21:30:30 [error] 1478591#0: *76 open() "/opt/nginx/html/test/index.html" failed (2: No such file or directory), client: 112.23.101.156, server: localhost, request: "GET /test/index.html HTTP/1.1", host: "118.25.7.84"

为什么会是/opt/nginx/html/test/index.html这个目录,时因为nginx默认的根目录是/opt/nginx/html,前边的配置没有起作用。
下面看后边的/

location ^~ /test {
    root   /opt;
}

重启后访问http://118.25.7.84/test/index.html,可以正常访问。

以上测试说明:uri前边的/不能省略,uri后边的/可以省略

proxy_pass

proxy_pass区别于rootalias,是将请求反向代理到指定的url。
首先用node启一个服务。

const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();

app.use(serve(__dirname + '/static/'));

app.listen('10010');

建一个static文件夹里边放一个index.html内容为proxy_pass test。 修改nginx.conf

location ^~ /test-proxy/ {
    proxy_pass http://localhost:10010/;
}

访问http://118.25.7.84/test-proxy/index.html
访问的是http://localhost:10010/index.html
proxy_pass后边有没有/是不一样的。
static目录下新建一个test-proxy目录,里边放一个index.html内容为proxy test 1
修改nginx配置文件

location ^~ /test-proxy/ {
    proxy_pass http://localhost:10010;   #这里少了个/
}

再次访问访问http://118.25.7.84/test-proxy/index.html


发现访问的是/static/test-proxy/index.html,即http://localhost:10010/test/proxy/index.html
我们再把proxy_pass后边加一级path看一下

location ^~ /test-proxy2/ {
    proxy_pass http://localhost:10010/proxy2/;
}

然后在static下新建一个/proxy2/index.html内容为proxy test 2。 访问http://118.25.7.84/test-proxy2/index.html
可以看到请求被反向代理到http://localhost:10010/proxy2/index.html
还有一种情况就是proxy_pass带路径但是最后没有/

location ^~ /test-proxy3/ {
    proxy_pass http://localhost:10010/proxy3;
}

http://118.25.7.84/test-proxy3/index.html
这个和alias一样会被反向代理到http://localhost:10010/proxy3index.html