目錄
1. 功能描述
2. 代碼實現
3. 問題解決
4. 最終效果
一、功能描述
- 實現: 在同一端口下部署一個react項目和一個vue項目,通過訪問
/
或/home
來訪問vue項目,通過訪問/portfolio
路徑來訪問react項目。 - 版本:
nginx/1.16.1
、react/16.13.1
、react-router-dom/5.2.0
、vue/2.6.11
、vue-router/3.4.9
。
二、代碼實現
react項目
1、package.json中增加配置homepage字段,以域名www.abc.cn為例
{
"homepage": "https://www.abc.cn/portfolio"
}
2、BroserRouter中配置basename屬性
//其他引入項省略
// 引入路由組件
import {
BrowserRouter as Router,
Switch,
Route
} from 'react-router-dom';
const App = () => {
return (
// 增加basename屬性
<Router basename="/portfolio">
<div className={styles.app}>
<LeftNav />
<div className={styles.content}>
<Switch>
<Route path="/:routerid" exact>
<DemoList />
</Route>
<Route path="/:routerid/:demo" exact>
<DemoDetail />
</Route>
<Route path="/" exact>
<Home />
</Route>
</Switch>
<CopyRight />
</div>
</div>
</Router>
)
}
export default App
vue項目
1、router中配置基礎路徑
const router = new VueRouter({
mode: 'history',
base: '/home', //基礎路徑
routes
});
2、vue.config.js(項目中沒有該文件的,可以在項目根目錄下創建)中配置基礎路徑
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/home'
: '/',
// 其他配置內容省略
}
Nginx配置
nginx.conf中相關配置(我的nginx頁面根目錄為/data/www
,vue項目部署在/data/www/home
目錄下,react項目部署在/data/www/portfolio
目錄下)
server {
listen 80;
server_name <your_server_name>;
root /data/www;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
# http to https
return 301 https://$host$request_uri;
# /重定向到/home
location / {
rewrite / /home permanent;
}
location /home {
index index.html index.htm;
try_files $uri $uri/ /home/index.html;
}
location /portfolio {
index index.html index.htm;
try_files $uri $uri/ /portfolio/index.html;
}
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
# 如果沒有配置ssl或者不使用https可以忽略下列配置
server {
listen 443 ssl;
server_name <your_server_name>;
root /data/www;
# ssl證書相關配置
ssl_certificate "/etc/nginx/cert/server.crt";
ssl_certificate_key "/etc/nginx/cert/server.key";
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
rewrite / /home permanent;
}
location /home {
index index.html index.htm;
try_files $uri $uri/ /home/inex.html;
}
location /portfolio {
index index.html index.htm;
try_files $uri $uri/ /portfolio/index.html;
}
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
三、問題解決
如上將兩個項目部署在二級目錄后,react項目下的子路由可以正常訪問,且刷新訪問也正常。vue項目的子路由通過<router-link></router-link>
組件可以正常訪問,但是刷新后會報“500 Internal Server Error”,可以通過下面方式解決。
修改nginx.conf中部分配置:
location /home {
index index.html index.htm;
try_files $uri $uri/ @router;
}
location @router {
rewrite ^.*$ /home/index.html last;
}