学习 NGINX

摘要:
如果没有常规匹配,请使用之前存储的最长前缀。例如,根据所请求的IP地址和报头信息提供不同的服务。重写基于正则表达式重写uri。我不知道我是否理解重写的两个参数。last–停止在当前服务器或位置上下文中执行写方向,但NGINXPlus搜索与写的URI匹配的位置,并应用新位置的任何重写方向。break–与break指令类似,停止在当前上下文中处理新的写方向,并取消对与新URI匹配位置的搜索。新位置中的重写指令不会执行。last:第一次重写生效后,将不再在当前位置或服务器中执行重写。然而,rewritenouri也将从一开始就经历重新编织的扫描和修改过程。索引文件若要设置索引文件,NGINX会检查其是否存在,然后对通过将索引文件的名称附加到基URI而获得的URI进行内部重定向。内部重定向结果将显示在新搜索的错误位置,并且可以在以下示例中找到其他位置:location/{root/data;indexindex.htmlix.php;}location~.php{fastcgi_passlocalhost:8000;…}这里,如果URI是请求/path/,And/data/path/index。htmldoesnotexist/data/path/index.phpdo,internalrirectto/path/index。php映射到第二个位置。因此,请求被执行。访问/,重定向变为/index.php。上面重写后的uri相同。再次按位置搜索并重写。

At a high level, configuring NGINX Plus as a web server is a matter of defining which URLs it handles and how it processes HTTP requests for resources at those URLs. At a lower level, the configuration defines a set of virtual servers that control the processing of requests for particular domains or IP addresses. 

NGINX Plus can send traffic to different proxies or serve different files based on the request URIs. These blocks are defined using the location directive placed within a server directive.

There are two types of parameter to the location directive: prefix strings (pathnames) and regular expressions. 

URI 匹配逻辑

regular expressions 比 prefix strings 优先级大。

测试所有 prefix uris。

如果匹配上了完全匹配 "=",返回结果。

If the ^~ (caret-tilde) modifier prepends the longest matching prefix string, the regular expressions are not checked. (没看懂)

测试完所有 prefix uris 之后,储存最长匹配表达式,进行正则匹配。

如果正则匹配成功,返回。

如果没有一个正则匹配,使用之前储存的最长的 prefix uri。

Directives 继承关系

For most directives, a context that is defined inside another context (a child context) inherits the values of directives included at the parent level. To override a value inherited from the parent, include the directive in the child context. For more information on context inheritence, see the documentation for the proxy_set_header directive.

Location 中处理请求

通过 Location directives 处理请求,比如是提供静态资源,还是转向代理服务器。

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

    location / {
        proxy_pass http://www.example.com;
    }
}

 使用变量

使用变量来区分处理不同环境下的请求。比如根据请求的 ip,头部信息等提供不同的服务。

rewrite

根据正则表达式重写 uri。

说下我对 rewrite 的两个参数的理解,不知道对不对。

  • last – Stops execution of the rewrite directives in the current server or location context, but NGINX Plus searches for locations that match the rewritten URI, and any rewrite directives in the new location are applied (meaning the URI can be changed again).
  • break – Like the break directive, stops processing of rewrite directives in the current context and cancels the search for locations that match the new URI. The rewrite directives in the new location are not executed.

last: 第一个 rewrite 生效后,在当前的 location 或 server 中不再执行 rewrite 了。但是 rewritten uri(经过 rewrite 后的结果)还会从头走一遍 rewirte 的扫描、修改过程。

break: 相比 last,rewritten uri 不再进入 rewrite 扫描。

Index file

To return the index file, NGINX checks for its existence and then makes an internal redirect to the URI obtained by appending the name of the index file to the base URI. The internal redirect results in a new search of a location and can end up in another location as in the following example:

location / {
    root /data;
    index index.html index.php;
}

location ~ .php {
    fastcgi_pass localhost:8000;
    ...
}

Here, if the URI in a request is /path/, and /data/path/index.html does not exist but /data/path/index.php does, the internal redirect to /path/index.php is mapped to the second location. As a result, the request is proxied.

访问 /,重定向变成 /index.php。/index.php 再次被 location 中搜索。上面的 rewrite 之后的 uri 也是一样,重新被 location, rewrite 搜索。

try_files

The try_files directive can be used to check whether the specified file or directory exists and make an internal redirect, or return a specific status code if they don’t. For example, to check the existence of a file corresponding to the request URI, use the try_files directive and the $uri variable as follows:

server {
    root /www/data;

    location /images/ {
        try_files $uri /images/default.gif;
    }
}

The file is specified in the form of the URI, which is processed using the root or alias directives set in the context of the current location or virtual server. In this case, if the file corresponding to the original URI doesn’t exist, NGINX makes an internal redirect to the URI specified in the last parameter, returning /www/data/images/default.gif.


如果要找的静态文件不存在,返回默认的静态文件。并且状态码是 200 而不是 304,因为这个重定向是内部重定向,客户端并不知情。

如果默认的静态文件不存在,我本地返回的 500。原因是构成了死循环

rewrite or internal redirection cycle while internally redirecting to "/images/default.jpg"

也可以自定义错误码,当 try_files 所有文件都没有找到的时候

location / {
    try_files $uri $uri/ $uri.html =404;
}

 reverse proxy

用途

负载均衡

从不同网站获取内容并展示,不太理解

以非 HTTP 协议传递请求。Supported protocols include FastCGIuwsgiSCGI, and memcached.

传递请求

location /some/path/ {
    proxy_pass http://www.example.com/link/;
}

This example configuration results in passing all requests processed in this location to the proxied server at the specified address. This address can be specified as a domain name or an IP address. The address may also include a port:

location ~ .php {
    proxy_pass http://127.0.0.1:8000;
}

Note that in the first example above, the address of the proxied server is followed by a URI, /link/. If the URI is specified along with the address, it replaces the part of the request URI that matches the location parameter. For example, here the request with the /some/path/page.html URI will be proxied to http://www.example.com/link/page.html. If the address is specified without a URI, or it is not possible to determine the part of URI to be replaced, the full request URI is passed (possibly, modified).

什么情况下会传递处理后的 URI,什么情况下会传递完整的 URI 过去?

代理服务器在同一个 NGINX 中,为什么只有一条记录,代理的不应该也是一条吗?

本地测试了一下:

传递处理后的 URI 并补全

location /images-before-proxy {
    proxy_pass http://localhost:8081/images/;
}

 传递的是匹配后的地址,访问 http://localhost:8080/images-before-proxy/image_name.jpg --> 匹配到 image_name.jpg --> 将 image_name.jpg 补全到 http://localhost:8081/images/ --> http://localhost:8081/images/image_name.jpg

传递完整的 URI

将配置改成

location /images-before-proxy {
    proxy_pass http://localhost:8081/; # 没有 /images/ 了
}

 访问 http://localhost:8080/images-before-proxy/image_name.jpg --> http://localhost:8081/images-before-proxy/image_name.jpg,返回 404 了。

访问 http://localhost:8080/images/image_name.jpg --> http://localhost:8081/images/image_name.jpg,返回 200。

那我现在理解成,只要域名或者 IP 地址跟了后缀,就会传递匹配后的 URI 并补全到 proxied uri 后面。

传递请求头部

NGINX 会擦除所有值为空的头部。根据这个特性,你如果不想传递某些头部,就将其设置为空。proxy_set_header Accept-Encoding "";

设置时可以读取 NGINX 自定义变量

缓冲区

NGINX 储存从 proxied server 过来的响应,直至响应完全被接收,才会发给客户端。这样能提高性能。

如果关闭缓存,那么响应会同步的发送给客户端,即从收到代理服务器后就立刻发送给客户端。

出口IP

作为客户端,服务器连接代理服务器的地 IP 址。当代理服务器只接受某些 IPs 的时候有用。

压缩

压缩能有效地减少传输数据量,但同时会增加客观的处理负担从而对性能不利。NGINX 在发送响应前会压缩,但不会压缩已经被压缩的数据。

压缩的参数:是否压缩、需要压缩的 MIME type、最小压缩长度。

默认情况下,NGINX 不压缩发给代理的响应。通过 Via 首部识别请求是否来自代理。使用 gzip_proxied 命令设置。比如压缩代理服务器不会储存的数据(为什么?)

gzip_proxied no-cache no-store private expired auth;

解压

有些客户不会解压,需要我们帮它解压好。有些客户能解压的,我们就不帮它解压(节省带宽)。

通过 gunzip 打开。注意事项:If enabled, the following directives are also taken into account when determining if clients support gzip:gzip_http_versiongzip_proxied, and gzip_disable

意思是,如果同时打开了解压和压缩,对于支持 gzip 的客户,数据还是压缩的;只有对于不支持的客户,才会解压。

尝试一下,压缩开关打开,压缩类型选择所有,响应头头中带了

Content-Encoding:gzip
Content-Type:image/jpeg

大小是 19.7 KB。

关闭 gzip 后:

没有了 Content-Encoding:gzip

还是 19.7 KB,大小没变。

然后又尝试了一个 378KB 的图片,传输大小为 369 KB,开始关闭 gzip 后大小也无变化。系统是 MacOS,所以大小可能有出入。

发送压缩文件

开头提到,临时压缩文件会消耗资源,从而降低性能。所以,可以提前压缩好文件。把 gzip_static on; 打开,访问 /path/to/file,如果 /path/to/file.gz 存在,那么实际上返回的是 /path/to/file.gz,文件名默认还是 file。

我发现 try_fiels 会与这个冲突,从而返回默认的静态文件。

负载均衡

默认使用轮询算法

upstream myproject {
    server 127.0.0.1:8888 weight=3;
    server 127.0.0.1:8889;
}

server {
    listen 8011;
    server_name www.domain.com;
    location / {
      proxy_pass http://myproject;
}  

 在这两个端口,启动了 Tornado app,发现确实是 3-1, 3-1 的接收请求。  

如果要配置静态文件,需要在代理端口 8011 配置,而不是增加 server 监听 8888 或者 8889。应该变成这样

  server {
    listen 8011;
    server_name www.domain.com;
        location /images/ {
                root /data;
        }
    location / {
      proxy_pass http://myproject;
    }

  

免责声明:文章转载自《学习 NGINX》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇在 ASP.NET CORE 中使用 SESSION电话本小程序开发完成及感想 20111125下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

nginx配置时server_name配的不一样还能正常访问

  原先server_name 配的是api.test.toutiao.applet.rockysaas.com,监听的是80端口,http。后来域名改成了api-test.tbk.rockysaas.com,监听443,https。但是发现原先的api.test.toutiao.applet.rockysaas.com还能访问。 server { #...

解读nginx配置

nginx配置指令   main配置段常见的配置指令   分类:     正常运行必备的配置     优化性能相关的配置     用于调试及定位问题相关的配置     事件驱动相关的配置   正常运行必备的配置    1、user     Syntax:user user [group]:运行nginx所使用的用户     Default:user n...

Android Glide加载视频封面

/** *   context 上下文 *   uri 视频地址 *   imageView 设置image *   frameTimeMicros 获取某一时间帧 */ public void loadVideoScreenshot(final Context context, String ur...

docker镜像仓库

一,下载registry镜像并启动 $ docker pull registry $ docker run -d -v /opt/registry:/var/lib/registry -p 5000:5000 --restart=always --name registry registry 二,测试,查看镜像仓库中所有镜像 $ curl http...

CORS跨域实现思路及相关解决方案

本篇包括以下内容: CORS 定义 CORS 对比 JSONP CORS,BROWSER支持情况 主要用途 Ajax请求跨域资源的异常 CORS 实现思路 安全说明 CORS 几种解决方案 自定义CORSFilter Nginx 配置支持Ajax跨域 支持多域名配置的CORS Filter keyword:cors,跨域,ajax,403,fi...

nginx Access-Control-Allow-Origin 多域名跨域设置

2019-1-16 12:24:15 星期三 网站的静态文件(js, css, 图片, 字体等)是在一个单独的域名下的, 为了防止非法访问, 给nginx添加了跨域的控制, 也可以在PHP代码中添加 nginx指令: add header 1. 在location块中, 判断当前来源的域名($http_origin)是不是符合条件, 2. 符合条件的话就用...