nginx配置详解

1. nginx配置总览

一般来说nginx的配置文件位于/etc/nginx/nginx.conf,大体的结构如下


...              #全局块

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

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

大体的职责

1、全局块:配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。

2、events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。

3、http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。

4、server块:配置虚拟主机的相关参数,一个http中可以有多个server。

5、location块:配置请求的路由,以及各种页面的处理情况。

一份默认的nignx配置文件如下

# 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。

$ 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操作。

worker_processes number | auto;
  • number, 指定 Nginx 进程最多可产生的 worker process 数
  • auto, Nginx 自动

查看物理cpu个数

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

查看逻辑cpu个数

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

查看下进程情况,有 一个master进程,两个worker进程

$ 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;

1、include

用来设定文件的mime类型,类型在配置文件目录下的mime.type文件定义,来告诉nginx来识别文件类型。

2、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;
    }   
}

1、server 标志定义虚拟主机开始。

2、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;

3、server_name 用来指定IP地址或者域名

多个域名之间用空格分,还可以使用通配符 * ,但通配符只能放到首尾,server_name中还能使用正则表达式,使用 ~ 开始

server_name ~^wwd+.einverne.info$;

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

对于不同的匹配方式,Nginx 按照如下优先级选择虚拟主机

准确匹配 server_name
通配符在开始时匹配 server_name 成功
通配符在结尾时匹配 server_name 成功
正则表达式匹配

在以上四种匹配方式中,如果 server_name 被处于同一优先级匹配方式匹配多次成功,则首次匹配成功的虚拟主机处理请求。

4、root 表示在这整个server虚拟主机内,全部的root web根目录。

5、index 全局定义访问的默认首页地址。

当找不到时候,会尝试按照index 指令后面定义的顺序查找文件,有则按照找到的文件运行。

index index.php index.html index.htm;

先查找 index.php,然后index.html ,最后index.htm

6、charset 用于设置网页的默认编码格式。

7、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;
    }   
}

分析下上面的配置,

1、 location / 是一个通用配置,如果没有优先级更高的匹配则都会走到这个通用路由下,

2、 try_files指令负责了重定向操作,

实际上这里做了动静分离,静态文件直接去相应目录拿,动态文件进行改写

如果是$uri$uri/的形式,则直接匹配到相应文件,找不到静态文件,则会尝试按照index的顺序,后置加上后进行匹配,比如这里首先匹配index.php,如果匹配上则送入location ~ .php$路由下。

如果不是$uri$uri/的形式的话,则中间加个index.php,然后拼接上和参数,此时有了index.php,根据匹配规则会被送到location ~ .php$路由下。

3、 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

原文地址:https://www.cnblogs.com/redirect/p/10066742.html