Nginx 部署前后端项目
Siona
Nginx 部署前后端项目
部署前端项目
1. Nginx 配置文件
# Nginx 配置文件所在路径【配置过的,如果没有可以去默认路径找 /usr/local/nginx/conf/conf.d/】
cd /etc/nginx/conf.d/
vi 8085.conf
# /etc/nginx/conf/conf.d/8085.conf
# web
location /bf-vue {
alias /opt/webapps/bf-vue;
}
# 保存
ESC
:wq
# 重启 Nginx
nginx -t
nginx -s reload
2. Vue3 项目所需配置
// vite.config.ts
import {defineConfig} from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
},
/**
* 一定要配置项目基础路径,Nginx 上的 location /bf-vue 与之对应,所有的 assets 资源会从该文件夹下查找
* 注意:路由与 base public path 没有关系,路由只是 base public path 后面的 /#/ 【http://localhost:5173/bf-vue/#/】
* Base public path when served in development or production.
* @default '/'
* resource: index.d.ts -> UserConfig -> base?: string;
*/
base: '/bf-vue/'
});
部署后端项目
cd /usr/local/nginx/
# 创建 conf.d 配置文件夹,用于存放所有的子配置文件
mkdir conf.d

2. 在 conf.d 文件下创建子配置文件
cd /etc/nginx/conf.d/
# 端口命名
vi 8085.conf
8085.conf 文件内容
# /usr/local/nginx/conf/conf.d/8085.conf
server {
listen 8085;
server_name 192.168.10.106 127.0.0.1;
index index.html index.htm;
# 日志
access_log /data/logs/8085.access.log;
error_log /data/logs/8085.error.log;
# web
location /bf-vue{
alias /opt/webapps/bf-vue;
}
# server
location /bf-server/ {
proxy_pass http://127.0.0.1:8080/bf-server/;
}
}
3. 在 nginx.conf 中将子配置文件 include
# /usr/local/nginx/conf/nginx.conf
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
# 尽量写到最后的位置,原因待验证
include ./conf.d/*.conf;
}
4. 重启 Nginx
# 验证 nginx 配置文件是否正确
/usr/local/nginx/sbin/nginx -t
# 重启 nginx
/usr/local/nginx/sbin/nginx -s reload
5. 访问路径
# 访问后端 → nginx 配置后端 一定要前后都加 /bf-server/
# 本地访问
http://192.168.10.106:8080/file/list?folderId=1137839146744819712&pageNum=1&pageSize=10
# Nginx 配置之后的访问地址
http://192.168.10.106:8085/bf-server/file/list?folderId=1137839146744819712&pageNum=1&pageSize=10
# 外网地址,外网10098 映射 内网8085
http://121.37.171.238:10098/bf-server/file/list?folderId=1137839146744819712&pageNum=1&pageSize=10
# 端口就是 8085.conf 配置的端口