请求代理模式
proxy_pass中只有IP和端口, 称为不带URI, 如:proxy_pass http://1270.0.0.1:8080, 另外一种是端口号之后包含其他路径的, 如: proxy_pass http://127.0.0.1:8080/(哪怕只带了一个/) 或 proxy_pass http://127.0.0.1:8080/test
对于不带URI的方式, nginx会保留location中的路径部分, 如:
1
2
3
4location /api1/ {
proxy_pass http://127.0.0.1:8080;
}
http://127.0.0.1/api1/xxx -> http://127.0.0.1:8080/api1/xxx对于带URI的方式, nginx会对URL进行替换
1
2
3
4location /api2/ {
proxy_pass http://127.0.0.1:8080/;
}
http://127.0.0.1/api2/xxx -> http://127.0.0.1:8080/xxxhttp://127.0.0.1/api2/被替换成http://127.0.0.1:8080/, 再加上剩下的xxx, 最终成为http://127.0.0.1:8080/xxx又比如:
1
2
3
4location /api3/ {
proxy_pass http://127.0.0.1:8080/test;
}
http://127.0.0.1/api3/xxx -> http://127.0.0.1:8080/testxxxhttp://127.0.0.1/api3/被替换成了http://127.0.0.1:8080/test, 再加上剩余的xxx, 就变成了http://127.0.0.1:8080/testxxx
规则总结
nginx代理8080端口, 转发到8989端口, 客户端请求地址: http://localhost:8080/api/user, nginx配置格式如下:
1 | server { |
location和proxy_pass不同配置搭配, 转发结果如下:
| location /api | location /api/ | |
|---|---|---|
| proxy_pass http://localhost:8989; | http://localhost:8989/api/user | http://localhost:9809/api/user |
| proxy_pass http://localhost:8989/; | http://localhost:8989//user | http://localhost:8989/user |
| proxy_pass http://localhost:8989/service; | http://localhost:8989/service/user | http://localhost:8989/serviceuser |
| proxy_pass http://localhost:8989/service/; | http://localhost:8989/service//user | http://localhost:8989/service/user |
建议: location 和 proxy_pass结尾斜线保持一致
本地资源模式
1 | location / { |
1 | # location 和 root 结尾有没有斜线都一样 |
1 | location /img { |
root配置时, 访问的资源是root+location目录下的
alias配置时, 访问的资源是alias目录下. 如果Path不加斜线则不影响, 如果Path以斜线结尾, alias必须以斜线结尾
nginx路由匹配规则
常见的路由匹配符号有:
=:精确匹配^~:精确前缀匹配~:区分大小写的正则匹配;~*:不区分大小写的正则匹配/uri:普通前缀匹配/:通用匹配
1 | location = / { |
| 请求URI | 匹配路由规则 |
|---|---|
| http://localhost/ | 规则A |
| http://localhost/login | 规则B |
| http://localhost/register | 规则F |
| http://localhost/static/a.html | 规则C |
| http://localhost/static/files/a.txt | 规则X |
| http://localhost/a.png | 规则D |
| http://localhost/a.PNG | 规则E |
| http://localhost/img/a.gif | 规则D |
| http://localhost/img/a.tiff | 规则Y |
同优先级精确度越高, 优先级越高
同级别的定义顺序越靠前, 优先级越高
负载均衡配置
1 | upstream groups1 { |
典型配置
可以通过digitalocean的页面配置需要的功能, 然后下载生成好的配置文件
1 | user www-data; |