nginx 將請求指定到指定後端伺服器

2022-08-31 04:51:07 字數 1709 閱讀 2780

據url請求中(後面用header自定義的引數)的自定義引數(比如server_name=server1),將請求**到不同的後端(proxy_pass)伺服器。
看似簡單的需求,弄了半天弄不出來,本來想直接用 args 匹配到關鍵字然後提取出來,**到後端,但是 nginx 直接把 request_ur[都引數都丟到後端了,導致後端沒辦法處理 server_name, 想到的是用 lua 指令碼處理整個 $uri,把 server_name 這個引數去掉但是始終弄不出來,有空繼續搞。

nginx 配置

測試:

可以在access.log裡面看到到server1的伺服器上了

用 postman 也可以

用 modify header 外掛程式

lua 指令碼 [未成功]:

--

@author: richard

--@date: 2017-08-11 13:01:31

--@last modified by: richard

--@last modified time: 2017-08-11 14:40:58

function

set_request_uri()

local request_uri =ngx.var.request_uri;

local question_pos, _ = string.find(request_uri, '?'

)

local target = ""

if question_pos>0

then

local uri = string.sub(request_uri, 1, question_pos-1

)

local args = ngx.decode_args(string.sub(request_uri, question_pos+1

))

if args.server_name then

target =args.server_name

if target == nil

then

target = "_"

endargs.remove(args,server_name)

return uri .. '?'

.. ngx.encode_args(args), target

else

return

request_uri, _

endelse

return

request_uri, _

endend

return set_request_uri();

lua

linux安裝nginx到指定目錄

安裝依賴 yum install gcc yum install pcre devel yum install zlib zlib devel yum install openssl openssl devel 一鍵安裝上面四個依賴 yum y install gcc zlib zlib devel...

將stdout stderr匯入到指定檔案

在編寫程式中,經常用到stdout stderr作為輸出,通常stdout用於輸出程式執行正常時的資訊,stderr用於輸出程式出錯時的資訊。我們可以通過一些命令將stdout stderr在螢幕上的輸出匯入到指定的檔案。1 準備工作 帶有stdout stderr輸出的test.cpp test....

原始碼安裝nginx到指定目錄

yum install libaio ncurses gcc gcc c cmake ncurses devel wget yum install pcre devel zlib devel tar zxvf nginx 1.16.1.tar.gz cd nginx 1.16.1 configure...