1 nginx配置文件 文件結構
... #全局塊
events { #events塊 ...}
http #http塊
{
... #http全局塊
server #server塊
{
... #server全局塊
location [PATTERN] #location塊
{ ... }
location [PATTERN]
{ ... }
}
server
{ ... }
... #http全局塊
}
-
全局塊:配置影響nginx全局的指令。一般有運行nginx服務器的用戶組,nginx進程pid存放路徑,日志存放路徑,配置文件引入,允許生成worker process數等。
-
events塊:配置影響nginx服務器或與用戶的網絡連接。有每個進程的最大連接數,選取哪種事件驅動模型處理連接請求,是否允許同時接受多個網路連接,開啟多個網絡連接序列化等。
-
http塊:可以嵌套多個server,配置代理,緩存,日志定義等絕大多數功能和第三方模塊的配置。如文件引入,mime-type定義,日志自定義,是否使用sendfile傳輸文件,連接超時時間,單連接請求數等。
-
server塊:配置虛擬主機的相關參數,一個http中可以有多個server。
- location塊:配置請求的路由,以及各種頁面的處理情況。
還有比較常用的命令有include,將另一個配置文件包含起來。例如:include /etc/nginx/sites-enabled/*;
注意:當 server 子標簽和 location 子標簽中都有 root 指令時,location 的 root 指令不起作用。
2 location 語法規則
location [=|~|~*|^~] /uri/ { … }
location 匹配的優先級(與location在配置文件中的順序無關) = 精確匹配會第一個被處理。如果發現精確匹配,nginx停止搜索其他匹配。 普通字符匹配,正則表達式規則和長的塊規則將被優先和查詢匹配,也就是說如果該項匹配還需去看有沒有正則表達式匹配和更長的匹配。 ^~ 則只匹配該規則,nginx停止搜索其他匹配,否則nginx會繼續處理其他location指令。 最后匹配理帶有"~"和"~*"的指令,如果找到相應的匹配,則nginx停止搜索其他匹配;當沒有正則表達式或者沒有正則表達式被匹配的情況下,那么匹配程度最高的逐字匹配指令會被使用。
2 例子:nginx 通過訪問/images/upload/文件名.html 到本機目錄 /home/ubuntu/server/webapp/bbs/images/upload/文件名.html。配置如下
server { listen 80 default_server; listen [::]:80 default_server; charset utf-8 root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name _; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } location ^~/images/upload/{ root /home/ubuntu/server/webapp/bbs/; } }
說明:訪問 ${server_name}:${listen}/${location} 即 140.187.167.220:80/images/upload/ 時 實際是訪問服務器文件系統的 /home/ubuntu/server/webapp/bbs/images/upload/ 目錄下的文件
3 反向代理可以查看 nginx 反向代理說明 博客