一、打開nginx機器的nginx配置文件
命令:
locate nginx.conf
會列出所有nginx.conf文件的地址,
一般咱們要用的nginx配置文件是/usr/local/nginx/conf/nginx.conf
cd /usr/local/nginx/conf
vim nginx.conf
二、在文件中添加配置
1、添加配置
將所有域名為srv.android.xx.xx.com,路徑以/update開頭的請求,轉發到10.160.xx.xx這台真實后端服務上:
location ^~ /update {#匹配所有路徑以/update開頭的請求
access_log /search/odin/nginx/logs/diffy_access_log main; #設置log落地文件
proxy_set_header Host srv.android.xx.xx.com; #設置請求域名
proxy_pass http://10.160.xx.xx; #設置想要轉發的真實后端服務
}
2、一些配置示例
location = / { # 精確匹配 / ,主機名后面不能帶任何字符串
[ configuration A ] } location / { # 因為所有的地址都以 / 開頭,所以這條規則將匹配到所有請求
# 但是正則和最長字符串會優先匹配
[ configuration B ] } location /documents/ { # 匹配任何以 /documents/ 開頭的地址,匹配符合以后,還要繼續往下搜索
# 只有后面的正則表達式沒有匹配到時,這一條才會采用這一條
[ configuration C ] } location ~ /documents/Abc { # 匹配任何以 /documents/ 開頭的地址,匹配符合以后,還要繼續往下搜索
# 只有后面的正則表達式沒有匹配到時,這一條才會采用這一條
[ configuration CC ] } location ^~ /images/ { # 匹配任何以 /images/ 開頭的地址,匹配符合以后,停止往下搜索正則,采用這一條。
[ configuration D ] } location ~* \.(gif|jpg|jpeg)$ { # 匹配所有以 gif,jpg或jpeg 結尾的請求
# 然而,所有請求 /images/ 下的圖片會被 config D 處理,因為 ^~ 到達不了這一條正則
[ configuration E ] } location /images/ { # 字符匹配到 /images/,繼續往下,會發現 ^~ 存在
[ configuration F ] } location /images/abc { # 最長字符匹配到 /images/abc,繼續往下,會發現 ^~ 存在
# F與G的放置順序是沒有關系的
[ configuration G ] } location ~ /images/abc/ { # 只有去掉 config D 才有效:先最長匹配 config G 開頭的地址,繼續往下搜索,匹配到這一條正則,采用
[ configuration H ] } location ~* /js/.*/\.js
3、常用正則
-
.
: 匹配除換行符以外的任意字符?
: 重復0次或1次+
: 重復1次或更多次*
: 重復0次或更多次\d
:匹配數字^
: 匹配字符串的開始$
: 匹配字符串的介紹{n}
: 重復n次{n,}
: 重復n次或更多次[c]
: 匹配單個字符c[a-z]
: 匹配a-z小寫字母的任意一個
4、保存配置文件
按鍵Esc
:wq
5、重啟nginx服務
cd /usr/local/nginx/sbin/
./nginx -s reload
三、驗證
向nginx機器發送請求,驗證nginx轉發是否配置成功。
1、可以通過請求結果驗證
如下,能返回預期結果,證明nginx轉發配置成功。
2、還可以通過查看配置nginx時,設置的log文件,來驗證是否配置成功
cd /search/odin/nginx/logs tail -f diffy_access_log
可以看到,請求打過來了,證明,nginx配置成功。
初入職場熱愛分享的打工人一枚,請大家多多指教~~