nginx部署前端SPA應用實踐

隨着react,vue的普及,先後端分離以後,多采用nginx爲靜態服務器,並用nginx對api作反向代理,以實現前端SPA應用的部署。

nginx location 匹配規則

  • ~ 波浪線表示執行一個正則匹配,區分大小寫
  • ~* 表示執行一個正則匹配,不區分大小寫
  • ^~ 表示普通字符匹配,若是該選項匹配,只匹配該選項,不匹配別的選項,通常用來匹配目錄
  • = 進行普通字符精確匹配
  • @ 定義一個命名的 location,使用在內部定向時,例如 error_page, try_files

browserHistory 模式的刷新問題

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')
}

多個SPA的部署與重定向

首先約定發佈代碼目錄以下: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

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.
相關文章
相關標籤/搜索