【轉】Nginx 常用配置

nginx 之 proxy_pass詳解

原文地址
在nginx中配置proxy_pass代理轉發時,如果在proxy_pass後面的url加/,表示絕對根路徑;如果沒有/,表示相對路徑,把匹配的路徑部分也給代理走。

假設下面四種情況分別用 http://192.168.1.1/proxy/test.html 進行訪問。

第一種:

location /proxy/ {
    proxy_pass http://127.0.0.1/;
}

代理到URL:http://127.0.0.1/test.html

第二種(相對於第一種,最後少一個 / )

location /proxy/ {
    proxy_pass http://127.0.0.1;
}

代理到URL:http://127.0.0.1/proxy/test.html

第三種:

location /proxy/ {
    proxy_pass http://127.0.0.1/aaa/;
}

代理到URL:http://127.0.0.1/aaa/test.html

第四種(相對於第三種,最後少一個 / )

location /proxy/ {
    proxy_pass http://127.0.0.1/aaa;
}

代理到URL:http://127.0.0.1/aaatest.html

nginx部署前端SPA應用實踐

原文地址

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

nginx location 匹配規則

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

browserHistory 模式的刷新問題

browserHistory 路由模式下,使用history api可以在前端進行頁面跳轉,但是刷新的話,就需要對鏈接進行一個修復(重定向)
我們可以使用nginx 的 try_files 來實現:

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的重定向配置

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的部署與重定向

首先約定發佈代碼目錄如下:

/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之後的文件即可。

配置gzip_static

gzip_static on;

The ngx_http_gzip_static_module module allows sending precompressed files with the “.gz” filename extension instead of regular files.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章