nginx路由文件配置

nginx中文文档

Nginx 的请求处理有多个阶段,比如说rewrite、access、content等等,不同的配置字段属于不同的配置阶段,不同阶段的先后执行顺序不一样,例如rewrite在content阶段前面,就算你content阶段的内容在前面,也一样是rewrite先生效。

其中content阶段(根据URI查找内容)主要有index、autoindex、static三个先后次序。

匹配特性

贪婪原则

尽可能长的匹配路由。例如下面的配置,当访问路径/images/时,其实也会匹配到第一条规则,所以,长路径优先匹配。

server {
    location / {
        root /data/www;
    }

    location /images/ {
        root /data;
    }
}

代理配置

简单的代理案例如下:

server {
    listen 8080;//默认端口80
    root /data/upl;//所有路径导入到/data/upl下
    
    //proxy_pass字段用于表示代理
    location / {
        proxy_pass http://localhost:8080;
    }
    //~用于通配
    location ~ .(gif|jpg|png)$ {
    root /data/images;
}
}

同时可以设置FastCGI代理,主要配置参数有fastcgi_pass,fastcgi_param等。

更多具体的代理配置参考文档Module ngx_http_proxy_module

常用字段解析

  • ssi:服务器端嵌入,默认配置为off,当配置为on的时候,服务器在将html发送到浏览器之前会先解析,然后将文件中的ssi指令解析,解析执行后的html会发送给浏览器(常见的主要有include文件等等)。

  • aliasrootroot匹配是在制定目录地址下匹配,匹配结果为path/uri,alias是在会用制定内容替换掉匹配的路径。例如下例:

location ~ ^/weblogs/ {
    root /data/weblogs/abc;
}
location ~^/test/ {
    alias /data/static/
}

当请求的URI是/weblogs/index/a.html时,那么实际定位到的地址是/data/weblogs/abc/weblogs/index/a.html;
当请求的URI是/test/ddd/a.html时,那么实际定位的地址是/data/static/ddd/a.html

Notice:

  • 使用alias时,目录名后面一定要加"/"。
  • alias可以指定任何名称。
  • alias在使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用。
  • alias只能位于location块中。
  • index: 该指令通常用于指定首页文件,当在匹配location下找到index指定的文件时,会进行内部rewrite跳转,然后根据跳转后的新地址进行匹配location,否则放弃处理,交给下一阶段模块处理。
    例如:
    location / {
        root /var/www/;
        index index.html;
    }
 
    location /index.html {
        set $a 32;
        echo "a = $a";
    }

假设求情的URI为/,首先根据location,index配置生效,然后rewrite地址为/index.html,接着根据location配置,贪婪原则,首先匹配到/index.html然后输出a = 32

参考文献

  1. nginx中文文档
  2. Module ngx_http_proxy_module
  3. Nginx配置指令的执行顺序(七)
原文地址:https://www.cnblogs.com/omg-two/p/7137928.html