Nginx基礎語法及常用配置

2021-10-10 17:23:45 字數 2239 閱讀 1728

nginx一般為開箱即用, 除了nginx.conf,其餘配置檔案,一般只需要使用預設提供即可。

#全域性塊

worker_process # 表示工作程序的數量,一般設定為cpu的核數

worker_connections # 表示每個工作程序的最大連線數

events

#events塊

http #http塊

}}

每個指令必須有分號結束

#user administrator administrators;  #配置使用者或者組,預設為nobody nobody。

#worker_processes 2; #允許生成的程序數,預設為1

#pid /nginx/pid/nginx.pid; #指定nginx程序執行檔案存放位址

error_log log/error.log debug;

#制定日誌路徑,級別。這個設定可以放入全域性塊,http塊,server塊,級別以此為:debug|info|notice|warn|error|crit|alert|emerg

#錯誤頁

server

location ~ \.(html)$

location @page_not_found

}}

nginx常用內建繫結變數

http upstream模組中,可以通過 server 指令指定後端伺服器的 ip 位址和埠,同時還可以設定每個後端伺服器在負載均衡排程中的狀態。常用的狀態有:

當負載排程演算法為ip_hash時,後端伺服器在負載均衡排程中的狀態不能是backup

配置示例:

upstream webservers
上述配置中192.168.18.203不參與負載均衡,127.0.0.1:8080為備機,根據該權重配置,2

3\frac

32​的請求量會到192.168.18.202,另外1

3\frac

31​的請求量會到192.168.18.201

upstream支援的負載均衡演算法見負載均衡

rewrite 語法

如果location中rewrite後是對靜態資源的請求,不需要再進行其他匹配,一般要使用break或不寫,直接使用當前location中的資料來源,完成本次請求

如果location中rewrite後,還需要進行其他處理,如動態fastcgi請求(.php,.jsp)等,要用last繼續發起新的請求

配置示例:

server 

rewrite ^/web$ /web_static/index.html last;

rewrite ^/watch/index.htm$ $scheme: permanent;

location ^~ /web_static/

location ^~ /html/

}

費力的rewrites

不要知難而退,rewrite 很容易和正規表示式混為一談。 實際上,rewrite 是很容易的,我們應該努力去保持它們的整潔。 很簡單,不新增冗餘**就行了。

糟糕的配置:

rewrite ^/(.*)$  permanent;
好點兒的配置:

rewrite ^  permanent;
更好的配置:

return 301 

;

反覆對比下這幾個配置。 第乙個 rewrite 捕獲不包含第乙個斜槓的完整 uri。 使用內建的變數$request_uri,我們可以有效的完全避免任何捕獲和匹配。

Nginx常用的基礎配置

nginx的客戶端狀態 http stub status syntax stub status default context server,location 示例 location mystatus 目錄中選擇乙個隨機頁面展示 http random index syntax random ind...

nginx常用操作指令及配置說明

最近在做專案的時候用到了nginx,剛開始一頭霧水,踩了一天坑。在網上找了一些資料,這裡做下記錄。nginx常用指令 nginx s quit 優雅停止nginx,有連線時會等連線請求完成再殺死worker程序 nginx s reload 優雅重啟,並重新載入配置檔案nginx.conf ngin...

nginx常用配置

官檔 nginx的負載均衡主要依賴這個模組 ngx http upstream module 1 安裝好nginx 192.168.1.111 2 修改egrep v nginx.conf.default nginx.conf 對其進行修改 訪問server name的時候,會找listen埠,所有...