前提:在linux上安装好nginx服务器
项目结构: 前端使用vue 后端使用springboot
在linux下新建文件夹www/website (website是我的项目名)
前端打包:
npm run build:prod :前端打包vue项目,使用xftp上传到linux服务器
java springboot项目打包
然后把website.jar文件上传到linux服务器上
启动java项目(nohup后台运行,并指定日志文件)
nohup java -jar website.jar >/opt/website.log 2>&1 &
配置linux反向代理跨域和vue项目路径
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location / {
root /www/website/;
index index.html index.htm;
try_files $uri $uri/ /index.html; #如果当前URL($uri)存在就显示,如果不存在就跳转到index.html($uri/ /index.html)
}
location /prod-api/ {
proxy_pass http://localhost:8090/;
proxy_pass_request_headers on;
proxy_set_header Connection "";
client_max_body_size 30m;
client_body_buffer_size 128k;
proxy_redirect off;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_next_upstream http_502 http_504 error invalid_header;
}
}
注意:try_files $uri $uri/ /index.html;
#如果当前URL($uri)存在就显示,如果不存在就跳转到index.html($uri/ /index.html),解决vue项目部署后再刷新404问题
重启nginx服务
切换到安装目录
cd /usr/local/nginx/sbin
重启nginx
./nginx -s reload
补充:vue History路由模式下反向代理配置
server {
listen 80;
server_name somename alias another.alias;
location / {
root /www/website/dist;
index index.html index.htm;
try_files $uri $uri/ @router;#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
}
location /api {
proxy_pass http://127.0.0.1:8090;
index index.html index.htm index.jsp;
}
location @router {
rewrite ^.*$ /index.html last; #history路由模式下防止刷新404 nginx配置
}
error_page 405 =200 @405;
location @405 {
proxy_method GET;
proxy_pass http://127.0.0.1:80;
}
}