目前,前端开发一般选用单页面技术开发,如:VueJs、ReactJs等。这种开发技术的特点在于前端负责路由解析与匹配。
当用户输入URL,刷新页面时,浏览器按照假路由去向服务器请求文件,此时服务器需要返回index.html文件,否则将出现404错误。
部署一个单页面应用很简单
location / {
root html;
try_files $uri /index.html index.html
}
知识点:
- root,表示web服务器目录
- try_files,尝试匹配实际路由($uri),若找不到,则返回index.html
部署多个单页面应用
如果遇到更复杂的需求,部署多个单页面应用在同一台服务器,且同时使用80(或443)端口,应该如何处理呢?
目标
假定有2个单页面应用需要部署,并通过不同前缀进行定向访问。
-
https://abc.com/a/xxx
,访问a项目 -
https://abc.com/b/xxx
,访问b项目
策略
为达到上述效果,我们只需要在项目打包阶段和nginx网关配置阶段设置好项目前缀。
1、打包阶段
打包的关键点在于为文件引用地址加上各自的前缀。如:
- a项目中文件引用地址附加
/a/
前缀 - b项目中文件引用地址附加
/b/
前缀
实现方法:
output: {
filename: 'assets/[name].js',
path: resolve(__dirname, '../', 'dist'),
publicPath: '/a/'
}
知识点:
publicPath,为打包静态资源添加指定前缀。
官方说明:
`
The publicPath configuration option can be quite useful in a variety of scenarios. It allows you to specify the base path for all the assets within your application.
`
2、nginx网关阶段
server {
listen 80;
root html;
location ^~ /a/
{
try_files $uri /a/index.html;
}
location ^~ /b/ {
try_files $uri /b/index.html;
}
知识点:
语法规则 location [=|~|~*|^~] /uri/ { … }
符号 | 含义 |
---|---|
= | 开头表示精确匹配 |
^~ | 开头表示 uri 以某个常规字符串开头,理解为匹配 url 路径即可。nginx 不对 url 做编码,因此请求为/static/20%/aa ,可以被规则^~ /static/ /aa 匹配到(注意是空格) |
~ | 开头表示区分大小写的正则匹配 |
~* | 开头表示不区分大小写的正则匹配 |
/ | 通用匹配,任何请求都会匹配到 |
验证
1、准备2个独立的spa应用,并将publicPath分别配置为/a/
和/b/
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js",
publicPath: "/a/",
}
2、配置nginx网关路由匹配规则
server {
listen 80;
location ^~ /a/
{
root /usr/share/nginx/html;
try_files $uri /a/index.html;
}
location ^~ /b/ {
root /usr/share/nginx/html;
try_files $uri /b/index.html;
}
}
3、启动docker
<!--1、安装nginx 镜像-->
docker pull nginx:1.17.10
<!--2、运行容器-->
docker run --name nginx-demo -p 80:80 -v /Users/huahua/Documents/lian/code/multi-spa-demo/project-a/dist/:/usr/share/nginx/html/a:ro -v /Users/huahua/Documents/lian/code/multi-spa-demo/project-b/dist/:/usr/share/nginx/html/b:ro -v /Users/huahua/Documents/lian/code/multi-spa-demo/nginx.conf:/etc/nginx/nginx.conf:ro -d nginx:1.17.10
4、在浏览器访问验证
验证源代码参考github
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。