第一步:下載安裝nginx 官網(wǎng): http://nginx.org/en/
第二步:將自己的vue項目打包為dist文件夾;
第三步:解壓下載的nginx文件夾,使用cmd進(jìn)入到nginx文件夾下,使用指令start nginx啟動nginx服務(wù)器;
第四步:瀏覽器輸入localhost:80,查看nginx是否啟動;
第五步:進(jìn)入nginx/html文件夾下,刪除50.html和index.html文件,將vue項目打包玩的dist文件夾下的所有文件復(fù)制到nginx/html文件夾下;
第六步:刷新瀏覽器,項目啟動成功;
使用proxy_pass配置反向代理,在匹配到location配置的URL路徑后,轉(zhuǎn)發(fā)請求到proxy_pass配置額URL球碉,是否會附加location配置路徑與proxy_pass配置的路徑后是否有"/"有關(guān)躯泰,有"/"則不附加
location /test/ {
proxy_pass http://127.0.0.1:8080/;
}
請求/test/1.jpg,將會被nginx轉(zhuǎn)發(fā)請求到http://127.0.0.1:8080/1.jpg(未附加/test/路徑)俯抖。
進(jìn)階
1.在同一域名下監(jiān)聽不同端口,啟動不同項目;
第一步:將不同的項目打包dist,并重命名為app1, app2 ...
第二步:將項目文件夾移到nginx/html文件夾下;
第三步:打開nginx/conf/nginx.conf文件, 找到
server {
listen 8001;
# 監(jiān)聽的端口號;
server_name localhost;
# 服務(wù)器地址:可以使ip,對應(yīng)hosts文件
location / {
# localhost:8001 瀏覽器訪問根路徑,不可修改
root html/app1;
# 指定項目所在路徑html/項目名字
index index.html index.htm;
# 指定項目入口文件,一般默認(rèn)index.html
}
location = /app1/index.html {
# 瀏覽器訪問地址,指向項目文件夾下的index.html
root html/emms;
index index.html index.htm;
}
# 配置反向代理,解決跨域問題
location /api {
proxy_pass http://172.xx.xx.xx:8000;
}
}
server {
listen 8002;
# 監(jiān)聽的端口號;
server_name localhost;
# 服務(wù)器地址:可以使ip,對應(yīng)hosts文件
location / {
# localhost:8002 瀏覽器訪問根路徑,不可修改
root html/app2;
# 指定項目所在路徑html/項目名字
index index.html index.htm;
# 指定項目入口文件,一般默認(rèn)index.html
}
location = /app2/index.html {
# 瀏覽器訪問地址,指向項目文件夾下的index.html
root html/app2;
index index.html index.htm;
}
}
需要幾個項目復(fù)制幾個,修改為對應(yīng)的項目名稱
- 第四步:
nginx -s reload
重載nginx配置文件,重啟nginx
nginx -s stop
停止nginx,
如果報錯
nginx: command not found
則使用./nginx -s xxx
監(jiān)聽同一端口,不同路徑部署多個項目
- 將vue項目配置文件下的publicPath修改為: '/項目名稱/'
// vue.config.js
module.exports = {
publicPath: `/app1/`, // 打包后的文件路徑
outputDir: `dist/app1`, // 打包文件放置在dist文件夾下的app1文件夾
};
- 配置nginx.conf文件,路徑同上
server {
listen 8001;
# 監(jiān)聽的端口號;
server_name localhost;
# 服務(wù)器地址:可以使ip,對應(yīng)hosts文件
root html; #文件根路徑
# 第一個項目app1
location ^~/app1/ {
try_files $uri $uri/ /app1/index.html;
#訪問根路徑下的app1/index.html入口文件
}
#第二個項目app2
location ^~/app2/ {
try_files $uri $uri/ /app2/index.html;
#訪問根路徑下的app2/index.html入口文件
}
location /api1{
proxy_pass http://172.xx.xx.xx:8001;
}
location /api2 {
proxy_pass http://172.xx.xx.xx:8002;
}
}
- 其他操作同上
vue配置反向代理
vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://172.xx.xx.xx:8000',
changeOrigin: true,
pathRewrite: {
'^/api': '',
},
},
},
},
};