前后端分离部署(Vue + webpack + nginx + spring boot)

816 阅读2分钟
原文链接: blog.wheelchen.me:4443

前后端分离部署(Vue + webpack + nginx + spring boot)

前端

前端项目的框架是用vue-cli 生成的。

修改配置文件

重点需要关注config/index.js下的配置

build: {
  env: require('./prod.env'),
  index: path.resolve(__dirname, '../dist/index.html'),
  assetsRoot: path.resolve(__dirname, '../dist'),
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',
  productionSourceMap: true,
  productionGzip: false,
  productionGzipExtensions: ['js', 'css'],
  bundleAnalyzerReport: process.env.npm_config_report
},

重点关注以下几个参数

assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',

assetsRoot:构建输出目录 也就是构建后的东西都扔这里
assetsSubDirectory:资源子目录 除了index.html,其余的js img css都分在这里
assetsPublicPath:项目目录 / 是根目录的意思

打包

利用webpack进行打包

npm run build

nginx

server {
    listen       9999;
    server_name  localhost;

    charset utf-8;

	location / {

	  #项目打包目录
	  root /Users/wheelchen/www/dist/; 

	  index index.html;

	  try_files $uri $uri/ /index.html;
	}

	location /api {
		rewrite ^/api/(.*)$ /$1 break;
		proxy_pass http://localhost:8888;
	}
}

以下几点需要注意

注意指定 root目录 - 为打包后的根目录

注意进行跨域【CORS】转发设置 -

location /api/ {
	rewrite ^/api/(.*)$ /$1 break;
	proxy_pass http://localhost:8888;
}

rewrite

由于/api这个路由是我们擅自加的,在发送到目标服务前可以使用 rewrite来处理掉这个多余的路由

rewrite 的作用是修改 $uri,但要注意 rewrite 要有个重新匹配 location 的副作用。由于 proxy_pass 的处理阶段比 location 处理更晚,所以这里需要 break 掉,以防止 rewrite 进入下一次 location 匹配而丢失 proxy_pass。

proxy_pass

值得注意的是:proxy_pass 后面的 host 如果填写一个域名的话,这个域名将会在 nginx 启动时解析。

如:

location
 /api { 
    proxy_pass http://xxx;
}

则会报异常:

nginx: [emerg] host not found in upstream "xxx"

而且由于 nginx 解析域名是在启动时做的,所以在 nginx 启动之后修改域名的解析对 nginx 是不会生效的。

如果觉得让 nginx 启动时去查询 DNS 这件事不靠谱(我就不推荐这么做,因为 DNS 确实是不可控的),那么可以在 proxy_pass 时到某个 IP 上,

hostname 可以通过 porxy_set_header 指令强制设置 proxy 的 HTTP 请求中的 Host 字段来修改它,比如:

location
 /api { 
    proxy_set_header Host api.web-tinker.com; 
    proxy_pass http://127.0.0.1:8080;
}

另外还有个要注意的点。proxy_pass 默认使用的是 http 1.0,可以通过 proxy_http_version 指令让它使用 http 1.1,以便开启 keepalive 之类的功能。

location
 /api { 
    proxy_http_version 1.1; 
    proxy_pass http://127.0.0.1:8080;
}

PS: 其实私以为, 本不应该由nignx进行URL的重写,工作完全可以由前端完成,区别生产环境与开发环境的配置文件。

参考