目前web開發 使用一般前后端分離技術,並且前端負責路由。為了美觀,會采用前端會采用h5 history 模式的路由。但刷新頁面時,前端真的會按照假路由去后端尋找文件。此時,后端必須返回index(index.html)文件才不至於返回404。
nginx 部署一個單頁應用很簡單:
location / {
root html;
try_files $uri /index.html index.html;
}
root是web服務器目錄,try_files 為文件匹配,先找真實的地址($uri),如果找不到,再找index.html文件。
#此處注意,history模式不可以使用相對位置引入方式(./)
但如果幾個單頁應用同時需要部署在同一台電腦上,並且都需要占用80或者443端口,就不太容易了。
介紹2種相同ip端口部署多個單頁應用(前端路由)的方法。
- 使用子域名區分,此種方法最是簡單。但是限制也大,必須要買域名,或者修改訪問者電腦的hosts文件。
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;
}
}
-
采用路徑的第一個文件夾名字作為區分。例如:
https://aa.com/a/xx
與https://aa.com/b/xx
。采用a
與b
作為區分,分別表示不同的項目。
需要設置點:- 前端打包后的文件引用地址,需要加上
'/a/'
'/b/'
為前綴 。比如<script scr="/a/test.js"></script>
(webpack 為設置publicPath: '/a') - 前端的路由路徑必須加上
/a/
前綴:比如真正地址test.com/ss
,需改成test.com/a/ss
- 前端打包后的文件引用地址,需要加上
server {
listen 80;
root /root/test; #web服務器目錄;
location ^~ /a/{
try_files $uri /a/index.html; #如果找不到文件,就返回 /toot/test/a/index.html
}
location ^~ /b/{
try_files $uri /b/index.html; #如果找不到文件,就返回 /toot/test/b/index.html
}
}