Nginx同一个server部署多个单页应用静态资源问题

服务器配置仅开放80端口,目前已有根路径的资源配置,现在需要新加一套静态资源,即在同一个server下新加一套路径匹配

直接配置nginx如下,以下代码只是demo

{
    server {
        listen       80;
        server_name  localhost;
        
          location /  {
              root /root/static; #根服务资源
              index index.html;
              try_files $uri $uri/ /index.html;
          }
          
          location  /news { 
            alias  /home/www/news/dist/; # news服务资源
            index  index.html;
            try_files $uri $uri/ /index.html;
        }  
    }
}

root和alias的区别网上有大量资料,有兴趣可以自行了解,简单说来就是最终请求是root + location还是直接alias。

news项目是单页应用,路由模式是history的,结果在访问前端路由时请求走到了跟服务资源去了。这里要解释一下try_files的作用,它会按顺序检查文件或文件是否匹配,返回第一个匹配成功的结果,要注意的时如果都匹配不到,会进行一个内部重定向到最后一个参数,这里例子请求到的是 {host}/index.html,而不是{host}/news/index.html,location不会被添加进去,所以需要修改try_files最后参数为/news/index.html即可。

最终配置为

{
    server {
        listen       80;
        server_name  localhost;
        
          location /  {
              root /root/static; #根服务资源
              index index.html;
              try_files $uri $uri/ /index.html;
          }
          
          location  /news { 
            alias  /home/www/news/dist/; # news服务资源
            index  index.html;
            try_files $uri $uri/ /news/index.html;
        }
          
    }
}

猜你喜欢

转载自blog.csdn.net/cscj2010/article/details/128819949