nginx 一个端口布署多个单页应用(history路由模式)。

目前web开发 使用通常先后端分离技术,而且前端负责路由。为了美观,会采用前端会采用h5 history 模式的路由。但刷新页面时,前端真的会按照假路由去后端寻找文件。此时,后端必须返回index(index.html)文件才不至于返回404。html

nginx 部署一个单页应用很简单:

location / {
      root   html;
      try_files $uri /index.html index.html;
   }

root是web服务器目录,try_files 为文件匹配,先找真实的地址($uri),若是找不到,再找index.html文件。
#此处注意,history模式不能够使用相对位置引入方式(./)前端

但若是几个单页应用同时须要部署在同一台电脑上,而且都须要占用80或者443端口,就不太容易了。linux

介绍2种相同ip端口部署多个单页应用(前端路由)的方法。

  1. 使用子域名区分,此种方法最是简单。可是限制也大,必需要买域名,或者修改访问者电脑的hosts文件。webpack

    server {
        listen       80;
        server_name  aa.gs.com;  #子域名aa访问时
        localtion / {
           root E:/ee; #windows 路径,E盘下面ee文件为aa.gs.com的服务器目录。
           try_files $uri /index.html index.html;
        }
    }
    server {
       listen       80;
       server_name bb.gs.com; #访问子域名bb时。
       location / {
           root   /root/bb; # linux /root/bb文件夹做为服务器目录。
           try_files $uri /index.html index.html;
       }
    
    }
  2. 采用路径的第一个文件夹名字做为区分。例如:https://aa.com/a/xxhttps://aa.com/b/xx。采用ab做为区分,分别表示不一样的项目。
    须要设置点:nginx

  3. 前端打包后的文件引用地址,须要加上'/a/' '/b/'为前缀 。好比 <script scr="/a/test.js"></script>(webpack 为设置publicPath: '/a')web

  4. 前端的路由路径必须加上/a/前缀:好比真正地址test.com/ss,需改为test.com/a/sswindows

server {
       listen       80;
       root /root/test; #web服务器目录;
       location ^~ /a/{
         try_files $uri /a/index.html;  #若是找不到文件,就返回 /root/test/a/index.html
       }
       location ^~ /b/{
        try_files $uri /b/index.html; #若是找不到文件,就返回 /root/test/b/index.html
       }
      
  }