nginx location

nginx location配置问题

 

场景:nginx 作为网关服务,nodejs服务作为后台服务

     domain.com/ 对接后台API

   如 domain.com/company/:id,  domain.com/user/:id 等

修改需求如下:domain.com/ 输出index.html 展示官网;nginx承担前端静态服务

 

理想情况是 /api 区分接口请求与非接口请求。为不带来较大影响,现需要nginx识别出 / 与 /**/** , 并在 / 请求时正常输出静态页面。

 

   location 配置如下:

1 location = / {
2     root /home/index/;
3     index index.html index.htm;
4 }
5 
6 
7 location ~* / {
8      proxy_pass http://127.0.0.1:3000;
9 }

 

理想与现实总是有差距,当前配置经过实验后任然无法如预期的样子。domain.com/ 的请求任然会被转发到3000的服务中。

发生了什么?为什么会这样呢?

 

经过查阅相关文档发现,

1 location = / {
2      root /home/index/;
3      index index.html index.htm;
4 }

location = / 为精确匹配;

当nginx匹配到 domain.com/ 时会捕获该请求;

捕获后在nginx内部会按照配置转化为 domain.com/index.html;

此时,原有的配置会将domain.com/index.html 的url 匹配为 location ~* / 进而转发给 3000服务

 

了解这一变化后即可采取对应措施,拦截.html, .css, .js 等静态资源请求映射到对应的资源文件夹。

 1      location = / {
 2         root /home/index/;
 3         index index.html index.htm;
 4      }
 5 
 6 
 7     location ~ \.html$ {
 8         root /home/index/;
 9         index index.html;
10     }
11 
12     location ~* / {
13         proxy_pass http://127.0.0.1:3000;
14     }    

 

至此, domain.com/ 即可展示官网, domain.com/**/** 任然可以转发至3000服务不受影响。 

 

 

        

 

posted @ 2020-02-25 21:46  不忘初心~  阅读(212)  评论(0编辑  收藏  举报