nginx 动态文件夹解析

416 阅读1分钟

1.起因

所有项目都是在同一个服务和端口下,并且文件夹都是遵循规范部署。 如下

location /aaa {
    alias  html/aaa/dev;
    index  index.html index.htm;
    add_header Cache-Control no-cache;
    try_files $uri $uri/ /aaa/index.html;
}
location /bbb {
    alias  html/bbb/dev;
    index  index.html index.htm;
    add_header Cache-Control no-cache;
    try_files $uri $uri/ /bbb/index.html;
}

当新增一个项目都要重复copy配置,而且要reload服务。

联想到tomcat在webapps下面放多少个就能根据文件夹访问多少个项目,不用刻意配置和reload,想达到这个效果。

2.思路

通过$request_uri 匹配当前的url地址如: http://127.0.0.1:8080/aaa/nn/mmm.html 实现动态判断路径解析,出第一个aaa的文件夹路径。然后吧aaa作为变量同步配置到对应的配置项里

3.前期准备

安装 nginx-module-echo ,方便调整,安装方法 看这里 echo插件安装

4.通过正则匹配$request_uri

 server {
      listen       8080;
      server_name  127.0.0.1; 
        location / {
             default_type text/html;
              echo "$request_uri";   
            if ($request_uri ~* /(\S*?)/ ) # 
            { 
                echo "math...ok."; 
                set $my_url $1;
                echo <br>$my_url;
                echo "math...end."; 
            }
        }
    } 
}

5.效果

打开浏览器愉快的访问 image.png

image.png

6.踩过的坑

  • alias 不能放在if条件里面
  • echo 打印的时候优先打印if里面的内容,没有再打印外部echo
  • location = / {} 配置 使用root 配置会找不到文件夹