随着react,vue的普及,先后端分离以后,多采用nginx为静态服务器,并用nginx对api作反向代理,以实现前端SPA应用的部署。
browserHistory 路由模式下,使用history api能够在前端进行页面跳转,可是刷新的话,就须要对连接进行一个修复(重定向)
咱们能够使用nginx 的 try_files
来实现:javascript
location / { root /code/app1/build; index index.html index.htm; try_files $uri $uri/ /index.html; } location ^~ /app { alias /code/app2/build; index index.html; try_files $uri $uri/ /app/index.html; } location ^~ /api/ { proxy_pass http://api.site; }
webpackDevServer的重定向配置css
const basename = '/app'; devServer: { proxy: { '/api': { target: 'http://api.site', changeOrigin: true, secure: false } }, publicPath: basename, host: HOST, port: PORT, inline: true, historyApiFallback: { rewrites: [ { from: new RegExp(`^${basename}`), to: `${basename}/index.html` }, { from: /./, to: basename } ] }, disableHostCheck: true, contentBase: path.join(__dirname, 'build') }
首先约定发布代码目录以下:html
/publish_webapp/ |-- app1/ |-- index.html |-- static |-- app2/ |-- index.html |-- static
nginx 配置:前端
location ~* ^\/(\w+) { root /publish_webapp/; index index.html; try_files $uri $uri/ $uri/index.html /$1/ /$1/index.html; }
gzip on; gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
配合webpack在打包的时候压缩静态文件,使用webpack插件compression-webpack-plugin
因为在部署至nginx服务器以前使用了webpack生成了gizp压缩以后的文件,因此就不用使用nginx来压缩静态js了,nginx只须要配置,直接使用gzip以后的文件便可。vue
配置gzip_staticjava
gzip_static on;
The ngx_http_gzip_static_module module allows sending precompressed files with the “.gz” filename extension instead of regular files.