nginx配置詳解

[TOC]javascript

1. nginx配置總覽

通常來講nginx的配置文件位於/etc/nginx/nginx.conf,大致的結構以下php

...              #全局塊

events {         #NGINX工做模式
   ...
}

http      #http塊
{
    ...   #http全局塊
    server        #server塊
    { 
        ...       #server全局塊
        location [PATTERN]   #location塊
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局塊
}

大致的職責css

一、全局塊:配置影響nginx全局的指令。通常有運行nginx服務器的用戶組,nginx進程pid存放路徑,日誌存放路徑,配置文件引入,容許生成worker process數等。

二、events塊:配置影響nginx服務器或與用戶的網絡鏈接。有每一個進程的最大鏈接數,選取哪一種事件驅動模型處理鏈接請求,是否容許同時接受多個網路鏈接,開啓多個網絡鏈接序列化等。

三、http塊:能夠嵌套多個server,配置代理,緩存,日誌定義等絕大多數功能和第三方模塊的配置。如文件引入,mime-type定義,日誌自定義,是否使用sendfile傳輸文件,鏈接超時時間,單鏈接請求數等。

四、server塊:配置虛擬主機的相關參數,一個http中能夠有多個server。

五、location塊:配置請求的路由,以及各類頁面的處理狀況。

一份默認的nignx配置文件以下html

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on; 
    tcp_nopush          on; 
    tcp_nodelay         on; 
    keepalive_timeout   65; 
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;  
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.

        location / { 
        }   

        error_page 404 /404.html;
            location = /40x.html {
        }   

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }   
    }   

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

2. main模塊

2.1 配置用戶用戶組

指定Nginx Worker進程運行用戶以及用戶組前端

user user [group];
  • user, 可運行 Nginx 服務器的用戶
  • group, 指定可運行用戶組

當配置user nginx;時,使用root用戶啓動nginx,查看下進程狀況,發現master進程是root,worker進程是nginx。vue

$ ps -ef | grep nginx 
root      1190     1  0 Jul20 ?        00:00:00 nginx: master process /usr/sbin/nginx
nginx     1191  1190  0 Jul20 ?        00:00:42 nginx: worker process
nginx     1192  1190  0 Jul20 ?        00:00:47 nginx: worker process
root      7104  7049  0 16:52 pts/0    00:00:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn nginx

2.2 配置worker process 數

worker角色的工做進程的個數,master進程是接收並分配請求給worker處理。這個數值簡單一點能夠設置爲cpu的核數,也是 auto 值,若是開啓了ssl和gzip更應該設置成與邏輯CPU數量同樣甚至爲2倍,能夠減小I/O操做。java

worker_processes number | auto;
  • number, 指定 Nginx 進程最多可產生的 worker process 數
  • auto, Nginx 自動

查看物理cpu個數node

cat /proc/cpuinfo |grep "physical id"|sort |uniq|wc -l
1

查看邏輯cpu個數linux

cat /proc/cpuinfo |grep "processor"|wc -l
2

查看下進程狀況,有 一個master進程,兩個worker進程nginx

$ ps -ef | grep nginx 
root      1190     1  0 Jul20 ?        00:00:00 nginx: master process /usr/sbin/nginx
nginx     1191  1190  0 Jul20 ?        00:00:42 nginx: worker process
nginx     1192  1190  0 Jul20 ?        00:00:47 nginx: worker process
root      7104  7049  0 16:52 pts/0    00:00:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn nginx

當設置worker_processes auto;時,能夠看出nginx默認啓動的數量是和邏輯cpu數量一致的。

2.3 PID文件存放路徑

Nginx 進程做爲系統守護進程運行,在文件中保存當前運行程序主進程號,支持配置 PID

pid file_path;

pid文件的做用

(1) pid文件的內容:pid文件爲文本文件,內容只有一行, 記錄了該進程的ID。
(2) pid文件的做用:準確判斷進程是否正在運行,防止進程啓動多個副本。只有得到pid文件(固定路徑固定文件名)寫入權限(F_WRLCK)的進程才能正常啓動並把自身的PID寫入該文件中。其它同一個程序的多餘進程則自動退出。

2.4 錯誤日誌路徑

全局塊、http 塊 和 server 塊均可以對 Nginx 日誌進行配置

error_log file | stderr [debug | info | notice | warn | error |crit | alert | emerg];

日誌級別可選,從低到高 debug, info, notice, warn, error, crit, alert, emerg ,其中,debug輸出日誌最爲最詳細,須要注意的是 debug 須要編譯時使用 --with-debug 開啓。

2.5 引入其餘配置

Nginx 提供 include 配置來引入其餘文件

include file;

file 是要引入的配置文件,支持相對路徑和正則匹配

3. events模塊

3.1 use 用來指定Nginx的工做模式。

use select|poll|kqueue|epoll|resig|/dev/poll|eventport;

Nginx支持的工做模式有select、poll、kqueue、epoll、rtsig和/dev/poll。其中select和poll都是標準的工做模式,kqueue和epoll是高效的工做模式,不一樣的是epoll用在Linux平臺上,而kqueue用在BSD系統中,由於Mac基於BSD,因此Mac也得用這個模式,對於Linux系統,epoll工做模式是首選。

工做模式的簡介:

  • select: 這是一種標準的請求處理方法。若是一個平臺上缺乏相應的更加有效的方法,那麼Nginx會自動使用select方法。
  • poll: 這是一種標準的請求處理方法。若是一個平臺上缺乏相應的更加有效的方法,那麼Nginx會自動使用poll方法。
  • kqueue: 這是BSD家族操做系統上可用的一種高效的請求處理方法。可用於FreeBSD, OpenBSD, NetBSD和OS X。kqueue方法會忽略multi_accept。
  • epoll: 這是Linux系統上可用的一種高效的請求處理方法,相似於kqueue。它有一個額外的directive,那就是epoll_events。epoll_events指定了Nginx能夠向內核傳遞的事件數量。默認的值是512。

3.2 worker_connections 用於定義Nginx每一個進程的最大鏈接數

worker_connections number;

即接收前端的最大請求數。最大客戶端鏈接數由worker_processes和worker_connections決定,即Max_clients = worker_processes * worker_connections,在做爲反向代理時,Max_clients變爲:Max_clients = worker_processes * worker_connections / 4。

進程的最大鏈接數受Linux系統進程的最大打開文件數限制,在執行操做系統命令「ulimit -n 65536」後worker_connections的設置才能生效。

3.3 設置網路鏈接序列化,防止驚羣現象發生,默認爲on

accept_mutex on;

驚羣現象

主進程(master 進程)首先經過 socket() 來建立一個 sock 文件描述符用來監聽,而後fork生成子進程(workers 進程),子進程將繼承父進程的 sockfd(socket 文件描述符),以後子進程 accept() 後將建立已鏈接描述符(connected descriptor)),而後經過已鏈接描述符來與客戶端通訊。

那麼,因爲全部子進程都繼承了父進程的 sockfd,那麼當鏈接進來時,全部子進程都將收到通知並「爭着」與它創建鏈接,這就叫「驚羣現象」。大量的進程被激活又掛起,只有一個進程能夠accept() 到這個鏈接,這固然會消耗系統資源。

Nginx對驚羣現象的處理

Nginx 提供了一個 accept_mutex 這個東西,這是一個加在accept上的一把共享鎖。即每一個 worker 進程在執行 accept 以前都須要先獲取鎖,獲取不到就放棄執行 accept()。有了這把鎖以後,同一時刻,就只會有一個進程去 accpet(),這樣就不會有驚羣問題了。accept_mutex 是一個可控選項,咱們能夠顯示地關掉,默認是打開的。

3.4 worker_rlimit_nofile

因爲每個socket都會打開一個文件描述符,因此服務器能夠同時處理鏈接數量受到系統文件描述符數量的限制。若是nginx打開的socket數量超過了文件描述符的數量,那麼在error.log文件中會出現too many opened files錯誤。咱們能夠用下面的命令來查看文件描述符的數量:

$ ulimit -n

Nginx worker進程默認的用戶名是www-data,用戶www-data所擁有的文件描述符的數量要大於worker進程數量與worker_connections之乘積。 nginx有一個worker_rlimit_nofile directive,能夠用來設置系統可用的文件描述符。這與ulimit設置可用文件描述符的做用是同樣的。若是它們都設置了可用文件描述符,那麼worker_rlimit_nofile會覆蓋ulimit的設置。

worker_rlimit_nofile 20960;

查看操做系統對一個進程施加的限制,咱們能夠用命令讀取/etc/$pid/limits文件,$pid是進程的pid。

3.5 設置一個進程是否同時接受多個網絡鏈接,默認爲off

multi_accept on;

multi_accept可讓nginx worker進程儘量多地接受請求。它的做用是讓worker進程一次性地接受監聽隊列裏的全部請求,而後處理。若是multi_accept的值設爲off,那麼worker進程必須一個一個地接受監聽隊列裏的請求。

4. http模塊

4.1 定義 MIME TYPE 類型

瀏覽器使用 MIME Type 來區分不一樣的媒體類型, Nginx 做爲 Web 服務器,必須可以識別前端請求的資源類型。

include       mime.types;
default_type  application/octet-stream;

一、include

用來設定文件的mime類型,類型在配置文件目錄下的mime.type文件定義,來告訴nginx來識別文件類型。

二、default_type

設定了默認的類型爲二進制流,也就是當文件類型未定義時使用這種方式,例如在沒有配置asp的locate 環境時,Nginx是不予解析的,此時,用瀏覽器訪問asp文件就會出現下載窗口了。

如下是mime.types文件的內容,該文件中包含了瀏覽器可以識別的 MIME 類型,以及對應的文件後綴名。

types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/javascript                js; 
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

    application/font-woff                 woff;
    application/java-archive              jar war ear;
    application/json                      json;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai; 
    application/rtf                       rtf;
    application/vnd.apple.mpegurl         m3u8;
    application/vnd.ms-excel              xls;
    application/vnd.ms-fontobject         eot;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z; 
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/xspf+xml                  xspf;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
    application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp2t                            ts;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}

4.2 自定義 Access 日誌

與 error_log 不一樣的是,Nginx 進程運行時訪問日誌,由 Nginx 提供服務過程當中應答前端請求的日誌。

Nginx 服務器支持對服務日誌的格式、大小、輸出等進行配置,須要使用兩個配置 log_formataccess_log

配置日誌格式的語法是:

log_format format_name 'set_of_variables_to_define_format';

而且配置訪問日誌的語法是:

access_log /path/to/log_file format_name;		#simplest form 
//OR
access_log /path/to/log_file [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

4.2.1 log_format

自定義日誌格式

log_format format_name 'set_of_variables_to_define_format';
  • format_name : 給定義的格式起的名稱,應該是全局惟一的
  • set_of_variables_to_define_format自定義格式化字符串,也能夠增刪部分參數

默認的配置格式

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

實際產生的日誌

123.151.43.110 - - [02/Aug/2018:03:30:16 +0800] "GET / HTTP/1.1" 200 3700 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36" "-"

常見的內置變量

$remote_addr, $http_x_forwarded_for 記錄客戶端IP地址
$remote_user 記錄客戶端用戶名稱
$request 記錄請求的URL和HTTP協議
$status 記錄請求狀態
$body_bytes_sent 發送給客戶端的字節數,不包括響應頭的大小; 該變量與Apache模塊mod_log_config裏的「%B」參數兼容。
$bytes_sent 發送給客戶端的總字節數。
$connection 鏈接的序列號。
$connection_requests 當前經過一個鏈接得到的請求數量。
$msec 日誌寫入時間。單位爲秒,精度是毫秒。
$pipe 若是請求是經過HTTP流水線(pipelined)發送,pipe值爲「p」,不然爲「.」。
$http_referer 記錄從哪一個頁面連接訪問過來的
$http_user_agent 記錄客戶端瀏覽器相關信息
$request_length 請求的長度(包括請求行,請求頭和請求正文)。
$request_time 請求處理時間,單位爲秒,精度毫秒; 從讀入客戶端的第一個字節開始,直到把最後一個字符發送給客戶端後進行日誌寫入爲止。
$time_iso8601 ISO8601標準格式下的本地時間。
$time_local 通用日誌格式下的本地時間。

4.2.2 access_log

access_log path [format [buffer=size]];
  • path, 配置服務日誌的文件存放路勁及名稱
  • format 可選,自定義日誌格式,也能夠經過 log_format 配置指定好,直接引用格式名
  • size 臨時存放日誌的內存緩存區大小

可使用同一級別的access_log指令指定多個日誌,兩個日誌文件都會被記錄

access_log /var/log/nginx/access.log;
access_log /var/log/nginx/custom_log custom;

若是要取消記錄日誌功能,使用

access_log off;

4.3.3 error_log

前面在全局模塊已經提到過error_log命令,和access_log相似,error_log也是設置記錄日誌的指令。不過它記錄的是錯誤日誌。

該指令在 http, stream, server 和 location 段均可以被指定,能夠覆蓋更外面的段的設置。

error_log file | stderr [debug | info | notice | warn | error |crit | alert | emerg];

這些問題屬於不一樣的嚴重程度級別: 調試 , 信息 , 通知 , 警告 , 錯誤 (這是默認級別,全球工做), 暴擊 , 警報或重大事件 。

例如:

error_log /var/log/nginx/error_log warn;

這將指示Nginx記錄全部類型警告和更嚴重的日誌級別暴擊 , 警報和emerg消息的消息。

在下一個示例中,將會記錄暴擊 , 警報和緊急級別的消息。

error_log /var/www/example1.com/log/error_log crit;

和access_log相似,可使用同一級別的error_log指令指定多個日誌,兩個日誌文件都會被記錄

error_log  /var/www/example1.com/log/error_log  warn;
error_log  /var/log/nginx/example1.error_log  crit;

4.4 sendfile

當一個程序須要傳輸文件時,Linux內核首先將文件數據緩衝,而後將文件數據傳送給程序緩衝,最後程序將文件數據傳輸到目的地。Sendfile方法是一種數據傳輸的更高效的方法,數據在內核中的文件描述符之間傳輸,而不須要將數據傳輸給程序緩衝。這種方法的結果是改善了對操做系統資源的利用。

咱們能夠用sendfile directive來啓用sendfile方法,在http,server,location三個模塊均可以定義。

http {
 sendfile on ;
}

默認狀況下,sendfile 的值是on。

4.5 配置鏈接超時時間

用戶鏈接回話鏈接後, Nginx 服務器能夠保持打開一段時間,在超過這個時間以後,服務器會關閉該鏈接。

keepalive_timeout timeout [header_timeout];
  • timeout 對鏈接的保持時間
  • header_timeout 可選,在 Response 頭部 Keep-Alive 域設置超時時間

示例

keepalive_timeout 120s 100s;

5. server模塊

erver模塊是http的子模塊,它用來定一個虛擬主機,咱們先講最基本的配置,這些在後面再講。下面是一個簡單的server

server{
    server_name www.xxx.cn xxx.cn;
    listen 80; 
    #工程根目錄
    root /data/laravel-vue/public/;
    charset UTF-8;
    #日誌文件位置,本身選擇
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    index index.php index.html index.htm;

    #error_page 500 502 503 504 404 /missing.html;
    #error_page 403 =404 /missing.html;

    location / { 
        try_files $uri $uri/ /index.php$is_args$args;
    }   

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }   
}

一、server 標誌定義虛擬主機開始。

二、listen 用於指定虛擬主機的服務端口。

監聽端口,默認80,小於1024的要以root啓動。能夠爲listen *:80、listen 127.0.0.1:80等形式。

同時監聽IPv4和IPv6地址

listen [::]:80;

可是從nginx 1.3某個版本起,上面語句只是監聽ipv4地址,由於有個參數ipv6only是默認打開的,上面就至關於

listen [::]:80 ipv6only=on;  #改版後,只是監聽ipv6地址了

因此要同時監聽ipv4和ipv6

listen 80;
listen [::]:80;

三、server_name 用來指定IP地址或者域名

多個域名之間用空格分,還可使用通配符 * ,但通配符只能放到首尾,server_name中還能使用正則表達式,使用 ~ 開始

server_name ~^ww\d+\.einverne\.info$;

匹配 ww1.einverne.info 但不匹配 www.einverne.info

對於不一樣的匹配方式,Nginx 按照以下優先級選擇虛擬主機

準確匹配 server_name
通配符在開始時匹配 server_name 成功
通配符在結尾時匹配 server_name 成功
正則表達式匹配

在以上四種匹配方式中,若是 server_name 被處於同一優先級匹配方式匹配屢次成功,則首次匹配成功的虛擬主機處理請求。

四、root 表示在這整個server虛擬主機內,所有的root web根目錄。

五、index 全局定義訪問的默認首頁地址。

當找不到時候,會嘗試按照index 指令後面定義的順序查找文件,有則按照找到的文件運行。

index index.php index.html index.htm;

先查找 index.php,而後index.html ,最後index.htm

六、charset 用於設置網頁的默認編碼格式。

七、access_log 和 error_log 用來指定此虛擬主機的日誌存放路徑,前面說的比較詳細了,這裏的優先級高於http塊。

6 location塊

location模塊是nginx中用的最多的,也是最重要的模塊了,什麼負載均衡、反向代理等都與它相關,location根據它字面意思就知道是來定位的,定位URL,解析URL。

下面分析一份日常在用的站點配置。

server{
    server_name www.xxx.cn xxx.cn;
    listen 80; 
    #工程根目錄
    root /data/laravel-vue/public/;
    charset UTF-8;
    #日誌文件位置,本身選擇
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    index index.php index.html index.htm;

    #error_page 500 502 503 504 404 /missing.html;
    #error_page 403 =404 /missing.html;

    location / { 
        #第一種寫法
        try_files $uri $uri/ /index.php$is_args$args;
        #第二種寫法
        #try_files $uri $uri/ /index.php?$query_string;
    }   

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        #第一種寫法
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    #第二種寫法,區別在於第一種,include引入的配置已經包括上面的參數
    # include fastcgi.conf;
    }   
}

分析下上面的配置,

一、 location / 是一個通用配置,若是沒有優先級更高的匹配則都會走到這個通用路由下,

二、 try_files指令負責了重定向操做,

實際上這裏作了動靜分離,靜態文件直接去相應目錄拿,動態文件進行改寫

若是是$uri$uri/的形式,則直接匹配到相應文件,找不到靜態文件,則會嘗試按照index的順序,後置加上後進行匹配,好比這裏首先匹配index.php,若是匹配上則送入location ~ \.php$路由下。

若是不是$uri$uri/的形式的話,則中間加個index.php,而後拼接上和參數,此時有了index.php,根據匹配規則會被送到location ~ \.php$路由下。

三、 location ~ \.php$用來處理php動態語言

咱們啓動php-fpm,監聽9000端口

fastcgi_pass 127.0.0.1:9000;

就是說將請求轉發到9000端口,交給php-fpm處理,此時從nginx到php-fpm可能有點語言不通,須要翻一下,因此就有了下面的引入參數

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;

還有另外一種寫法,這裏面已經包括了SCRIPT_FILENAME參數

include fastcgi.conf;

7. 其它一些問題

上面介紹了nginx的基本配置,這一章節探討一些沒有講到的問題。

7.1 alias目錄和root目錄的區別:

配置demo:

location /test.html {
        root /data/ceshi/;
        # root /data/ceshi;路徑結尾加不加/,不影響結果
    }   
    
    location /xx/test.html {
        root /data/ceshi/;
    }
  • 瀏覽器訪問 xxx.com/test.html,實際訪問的是 /data/ceshi/test.html
  • 瀏覽器訪問 xxx.com/xx/test.html,實際訪問的是 /data/ceshi/xx/test.html

結論: root屬性,會把root的值(這裏是yyy)加入到訪問路徑(locaition)以前 配置demo:

location  /xxx {
    alias /data/ceshi/;    
    # alias /data/ceshi; 查看資料說必須加上/,不然會找不到文件,實測能夠找到,這裏本身能夠嘗試下。
}
  • 瀏覽器訪問 xxx.com/xxx,實際訪問的是 /data/ceshi
  • 瀏覽器訪問 xxx.com/xxx/test.html,實際訪問的是 /data/ceshi/test.html

結論:alias屬性,和root的邏輯不通,會把alias的值(這裏/data/ceshi/)替代訪問路徑匹配的部分(這裏是/xxx)

7.2 在寫location的時候,匹配url,加不加 /的探討

location /test/location /test 爲例

測試1:

location / { 
        return 601; 
        try_files $uri /index.php$is_args$args; 
    }   
 
    location /test { 
        return 602; 
    }   
 
    location /test/ { 
        return 603; 
    }
訪問 http://xxx.com/test   => 602

訪問 http://xxx.com/test/   => 603

測試2:

location / { 
        return 601; 
        try_files $uri /index.php$is_args$args; 
    }   
 
    location /test { 
        return 602; 
    }
訪問 http://xxx.com/test   => 602

訪問 http://xxx.com/test/   => 602

測試3:

location / { 
        return 601; 
        try_files $uri /index.php$is_args$args; 
    }   
 
    location /test/ { 
        return 603; 
    }
訪問 http://xxx.com/test   => 601

訪問 http://xxx.com/test/   => 603

7.3 nginx中的變量

$arg_name
請求中的的參數名,即「?」後面的arg_name=arg_value形式的arg_name

$args
請求中的參數值

$binary_remote_addr
客戶端地址的二進制形式, 固定長度爲4個字節

$body_bytes_sent
傳輸給客戶端的字節數,響應頭不計算在內;這個變量和Apache的mod_log_config模塊中的「%B」參數保持兼容

$bytes_sent
傳輸給客戶端的字節數 (1.3.8, 1.2.5)

$connection
TCP鏈接的序列號 (1.3.8, 1.2.5)

$connection_requests
TCP鏈接當前的請求數量 (1.3.8, 1.2.5)

$content_length
「Content-Length」 請求頭字段

$content_type
「Content-Type」 請求頭字段

$cookie_name
cookie名稱

$document_root
當前請求的文檔根目錄或別名

$document_uri
同 $uri

$host
優先級以下:HTTP請求行的主機名>」HOST」請求頭字段>符合請求的服務器名

$hostname
主機名

$http_name
匹配任意請求頭字段; 變量名中的後半部分「name」能夠替換成任意請求頭字段,如在配置文件中須要獲取http請求頭:「Accept-Language」,那麼將「-」替換爲下劃線,大寫字母替換爲小寫,形如:$http_accept_language便可。

$https
若是開啓了SSL安全模式,值爲「on」,不然爲空字符串。

$is_args
若是請求中有參數,值爲「?」,不然爲空字符串。

$limit_rate
用於設置響應的速度限制,詳見 limit_rate。

$msec
當前的Unix時間戳 (1.3.9, 1.2.6)

$nginx_version
nginx版本

$pid
工做進程的PID

$pipe
若是請求來自管道通訊,值爲「p」,不然爲「.」 (1.3.12, 1.2.7)

$proxy_protocol_addr
獲取代理訪問服務器的客戶端地址,若是是直接訪問,該值爲空字符串。(1.5.12)

$query_string
同 $args

$realpath_root
當前請求的文檔根目錄或別名的真實路徑,會將全部符號鏈接轉換爲真實路徑。

$remote_addr
客戶端地址

$remote_port
客戶端端口

$remote_user
用於HTTP基礎認證服務的用戶名

$request
表明客戶端的請求地址

$request_body
客戶端的請求主體
此變量可在location中使用,將請求主體經過proxy_pass, fastcgi_pass, uwsgi_pass, 和 scgi_pass傳遞給下一級的代理服務器。

$request_body_file
將客戶端請求主體保存在臨時文件中。文件處理結束後,此文件需刪除。若是須要之一開啓此功能,須要設置client_body_in_file_only。若是將次文件傳遞給後端的代理服務器,須要禁用request body,即設置proxy_pass_request_body off,fastcgi_pass_request_body off, uwsgi_pass_request_body off, or scgi_pass_request_body off 。

$request_completion
若是請求成功,值爲」OK」,若是請求未完成或者請求不是一個範圍請求的最後一部分,則爲空。

$request_filename
當前鏈接請求的文件路徑,由root或alias指令與URI請求生成。

$request_length
請求的長度 (包括請求的地址, http請求頭和請求主體) (1.3.12, 1.2.7)

$request_method
HTTP請求方法,一般爲「GET」或「POST」

$request_time
處理客戶端請求使用的時間 (1.3.9, 1.2.6); 從讀取客戶端的第一個字節開始計時。

$request_uri
這個變量等於包含一些客戶端請求參數的原始URI,它沒法修改,請查看$uri更改或重寫URI,不包含主機名,例如:」/cnphp/test.php?arg=freemouse」。

$scheme
請求使用的Web協議, 「http」 或 「https」

$sent_http_name
能夠設置任意http響應頭字段; 變量名中的後半部分「name」能夠替換成任意響應頭字段,如須要設置響應頭Content-length,那麼將「-」替換爲下劃線,大寫字母替換爲小寫,形如:$sent_http_content_length 4096便可。

$server_addr
服務器端地址,須要注意的是:爲了不訪問linux系統內核,應將ip地址提早設置在配置文件中。

$server_name
服務器名,www.cnphp.info

$server_port
服務器端口

$server_protocol
服務器的HTTP版本, 一般爲 「HTTP/1.0」 或 「HTTP/1.1」

$status
HTTP響應代碼 (1.3.2, 1.2.2)

$tcpinfo_rtt, $tcpinfo_rttvar, $tcpinfo_snd_cwnd, $tcpinfo_rcv_space
客戶端TCP鏈接的具體信息

$time_iso8601
服務器時間的ISO 8610格式 (1.3.12, 1.2.7)

$time_local
服務器時間(LOG Format 格式) (1.3.12, 1.2.7)

$uri
請求中的當前URI(不帶請求參數,參數位於$args),能夠不一樣於瀏覽器傳遞的$request_uri的值,它能夠經過內部重定向,或者使用index指令進行修改,$uri不包含主機名,如」/foo/bar.html」。

參考資料

https://www.jianshu.com/p/bed000e1830b

http://www.cnphp.info/nginx-embedded-variables-lasted-version.html

相關文章
相關標籤/搜索