Nginx入门

Nginx入门

基础

Nginx 下载

首先进入nginx的官方网站,找到下载地址,nginx的安装方式有多种,通过源码编译安装以及通过包安装,这里为了简单使用包安装,下载地址

Install the prerequisites:

sudo yum install yum-utils

To set up the yum repository, create the file named /etc/yum.repos.d/nginx.repo with the following contents:

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key

By default, the repository for stable nginx packages is used. If you would like to use mainline nginx packages, run the following command:

sudo yum-config-manager --enable nginx-mainline

To install nginx, run the following command:

sudo yum install nginxb

When prompted to accept the GPG key, verify that the fingerprint matches 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62, and if so, accept it.

#查看nginx的版本
nginx -v 
#查看nginx的版本,安装参数,位置,模块
nginx -V 
#查看yum方式安装的nginx的所有位置,文件
rpm -ql nginx

Nginx的特点

  • 采用io多路复用的epoll模型
  • Nginx轻量级
  • Nginx的CPU亲和性
  • Nginx的sendfile机制

Nginx 常用模块

ngx_http_stub_status_module

The ngx_http_stub_status_module module provides access to basic status information.

This module is not built by default, it should be enabled with the --with-http_stub_status_module configuration parameter.

Example Configuration
location = /basic_status {
    stub_status;
}

This configuration creates a simple web page with basic status data which may look like as follows:

Active connections: 1 
server accepts handled requests
 2 2 3 
Reading: 0 Writing: 1 Waiting: 0 
Directives
Syntax:**stub_status**;
Default:
Context:server, location

The basic status information will be accessible from the surrounding location.

In versions prior to 1.7.5, the directive syntax required an arbitrary argument, for example, “stub_status on”.

Data

The following status information is provided:

  • Active connections

    The current number of active client connections including Waiting connections.

  • accepts

    The total number of accepted client connections.

  • handled

    The total number of handled connections. Generally, the parameter value is the same as accepts unless some resource limits have been reached (for example, the worker_connections limit).

  • requests

    The total number of client requests.

  • Reading

    The current number of connections where nginx is reading the request header.

  • Writing

    The current number of connections where nginx is writing the response back to the client.

  • Waiting

    The current number of idle client connections waiting for a request.

Embedded Variables

The ngx_http_stub_status_module module supports the following embedded variables (1.3.14):

  • $connections_active

    same as the Active connections value;

  • $connections_reading

    same as the Reading value;

  • $connections_writing

    same as the Writing value;

  • $connections_waiting

    same as the Waiting value.

ngx_http_random_index_module

The ngx_http_random_index_module module processes requests ending with the slash character (‘/’) and picks a random file in a directory to serve as an index file. The module is processed before thengx_http_index_module module.

This module is not built by default, it should be enabled with the --with-http_random_index_module configuration parameter.

Example Configuration
location / {
    random_index on;
}
Directives
Syntax:**random_index** on | off;
Default:random_index off;
Context:location

Enables or disables module processing in a surrounding location.

ngx_http_sub_module

The ngx_http_sub_module module is a filter that modifies a response by replacing one specified string by another.

This module is not built by default, it should be enabled with the --with-http_sub_module configuration parameter.

Example Configuration
location / {
    sub_filter '<a href="http://127.0.0.1:8080/'  '<a href="https://$host/';
    sub_filter '<img src="http://127.0.0.1:8080/' '<img src="https://$host/';
    sub_filter_once on;
}
Directives
Syntax:**sub_filter** *string* *replacement*;
Default:
Context:http, server, location

Sets a string to replace and a replacement string. The string to replace is matched ignoring the case. The string to replace (1.9.4) and replacement string can contain variables. Several sub_filter directives can be specified on one configuration level (1.9.4). These directives are inherited from the previous level if and only if there are no sub_filter directives defined on the current level.

Syntax:**sub_filter_last_modified** on | off;
Default:sub_filter_last_modified off;
Context:http, server, location

This directive appeared in version 1.5.1.

Allows preserving the “Last-Modified” header field from the original response during replacement to facilitate response caching.

By default, the header field is removed as contents of the response are modified during processing.

Syntax:**sub_filter_once** on | off;
Default:sub_filter_once on;
Context:http, server, location

Indicates whether to look for each string to replace once or repeatedly.

Syntax:**sub_filter_types** *mime-type* ...;
Default:sub_filter_types text/html;
Context:http, server, location

Enables string replacement in responses with the specified MIME types in addition to “text/html”. The special value “*” matches any MIME type (0.8.29).

test case

在/usr/share/nginx/html/添加website.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>test sub modules</title>
</head>
<body>
    <!-- 访问127.0.0.1netes官网 -->
    <a href="https://127.0.0.1netes.io/">127.0.0.1netes</a> 
    <!-- 访问docker官网 -->
    <a href="https://www.docker.com/">docker</a>
    <!-- 访问srping官网 -->
    <a href="https://spring.io/">spring</a>
</body>
</html>

接下来修改配置文件default.conf,在location /添加相关的配置

server {
    listen       80;
    server_name  localhost;
    location / {
        sub_filter '<a href="https://127.0.0.1netes.io/">'  '<a href="https://$host/">'; 
        # sub_filter_last_modified on; 
        # sub_filter_once on;
        # sub_filter_types text/html;
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

浏览器访问http://127.0.0.1/website.html,查看页面源码,发现127.0.0.1netes的链接已经被修改了。

ngx_http_limit_conn_module

The ngx_http_limit_conn_module module is used to limit the number of connections per the defined key, in particular, the number of connections from a single IP address.

Not all connections are counted. A connection is counted only if it has a request being processed by the server and the whole request header has already been read.

Example Configuration
http {
    limit_conn_zone $binary_remote_addr zone=addr:10m;

    ...

    server {

        ...

        location /download/ {
            limit_conn addr 1;
        }
Directives
Syntax:**limit_conn** *zone* *number*;
Default:
Context:http, server, location

Sets the shared memory zone and the maximum allowed number of connections for a given key value. When this limit is exceeded, the server will return the error in reply to a request. For example, the directives

limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
    location /download/ {
        limit_conn addr 1;
    }

allow only one connection per an IP address at a time.

In HTTP/2 and SPDY, each concurrent request is considered a separate connection.

There could be several limit_conn directives. For example, the following configuration will limit the number of connections to the server per a client IP and, at the same time, the total number of connections to the virtual server:

limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;

server {
    ...
    limit_conn perip 10;
    limit_conn perserver 100;
}

These directives are inherited from the previous level if and only if there are no limit_conn directives on the current level.

Syntax:**limit_conn_log_level** info | notice | warn | error;
Default:limit_conn_log_level error;
Context:http, server, location

This directive appeared in version 0.8.18.

Sets the desired logging level for cases when the server limits the number of connections.

Syntax:**limit_conn_status** *code*;
Default:limit_conn_status 503;
Context:http, server, location

This directive appeared in version 1.3.15.

Sets the status code to return in response to rejected requests.

Syntax:**limit_conn_zone** *key* zone=*name*:*size*;
Default:
Context:http

Sets parameters for a shared memory zone that will keep states for various keys. In particular, the state includes the current number of connections. The *key* can contain text, variables, and their combination. Requests with an empty key value are not accounted.

Prior to version 1.7.6, a *key* could contain exactly one variable.

Usage example:

limit_conn_zone $binary_remote_addr zone=addr:10m;

Here, a client IP address serves as a key. Note that instead of $remote_addr, the $binary_remote_addr variable is used here. The $remote_addr variable’s size can vary from 7 to 15 bytes. The stored state occupies either 32 or 64 bytes of memory on 32-bit platforms and always 64 bytes on 64-bit platforms. The $binary_remote_addrvariable’s size is always 4 bytes for IPv4 addresses or 16 bytes for IPv6 addresses. The stored state always occupies 32 or 64 bytes on 32-bit platforms and 64 bytes on 64-bit platforms. One megabyte zone can keep about 32 thousand 32-byte states or about 16 thousand 64-byte states. If the zone storage is exhausted, the server will return the error to all further requests.

Syntax:**limit_zone** *name* *$variable* *size*;
Default:
Context:http

This directive was made obsolete in version 1.1.8 and was removed in version 1.7.6. An equivalent limit_conn_zone directive with a changed syntax should be used instead:

limit_conn_zone *$variable* zone=*name*:*size*;

test case

修改default.conf文件,添加相关的配置

limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn_zone $server_name zone=perserver:10m; 
server {
    listen       80;
    server_name  localhost;
    location / {
        limit_conn addr 1;
        limit_conn perserver 3; 
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

使用压力测试工具apache bench测试请求

ab -n 20 -c 20 http://127.0.0.1/website.html
# 这里的测试并没有通过,以后再做处理

这里涉及到了http协议的连接与请求

HTTP协议版本连接关系
HTTP1.0TCP不能复用
HTTP1.1顺序性TCP复用
HTTP2.0多路复用TCP复用

HTTP协议的连接与请求

  • HTTP请求建立在一次TCP连接基础上
  • 一次TCP请求至少产生一次HTTP请求
ngx_http_limit_req_module

The ngx_http_limit_req_module module (0.7.21) is used to limit the request processing rate per a defined key, in particular, the processing rate of requests coming from a single IP address. The limitation is done using the “leaky bucket” method.

Example Configuration
http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    ...

    server {

        ...

        location /search/ {
            limit_req zone=one burst=5;
        }
Directives
Syntax:**limit_req** zone=*name* [burst=*number*] [nodelay | delay=*number*];
Default:
Context:http, server, location

Sets the shared memory zone and the maximum burst size of requests. If the requests rate exceeds the rate configured for a zone, their processing is delayed such that requests are processed at a defined rate. Excessive requests are delayed until their number exceeds the maximum burst size in which case the request is terminated with an error. By default, the maximum burst size is equal to zero. For example, the directives

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

server {
    location /search/ {
        limit_req zone=one burst=5;
    }

allow not more than 1 request per second at an average, with bursts not exceeding 5 requests.

If delaying of excessive requests while requests are being limited is not desired, the parameter nodelay should be used:

limit_req zone=one burst=5 nodelay;

The delay parameter (1.15.7) specifies a limit at which excessive requests become delayed. Default value is zero, i.e. all excessive requests are delayed.

There could be several limit_req directives. For example, the following configuration will limit the processing rate of requests coming from a single IP address and, at the same time, the request processing rate by the virtual server:

limit_req_zone $binary_remote_addr zone=perip:10m rate=1r/s;
limit_req_zone $server_name zone=perserver:10m rate=10r/s;

server {
    ...
    limit_req zone=perip burst=5 nodelay;
    limit_req zone=perserver burst=10;
}

These directives are inherited from the previous level if and only if there are no limit_req directives on the current level.

Syntax:**limit_req_dry_run** on | off;
Default:limit_req_dry_run on;
Context:http, server, location

This directive appeared in version 1.17.1.

Enables the dry run mode. In this mode, requests processing rate is not limited, however, in the shared memory zone, the number of excessive requests is accounted as usual.

Syntax:**limit_req_log_level** info | notice | warn | error;
Default:limit_req_log_level error;
Context:http, server, location

This directive appeared in version 0.8.18.

Sets the desired logging level for cases when the server refuses to process requests due to rate exceeding, or delays request processing. Logging level for delays is one point less than for refusals; for example, if “limit_req_log_level notice” is specified, delays are logged with the info level.

Syntax:**limit_req_status** *code*;
Default:limit_req_status 503;
Context:http, server, location

This directive appeared in version 1.3.15.

Sets the status code to return in response to rejected requests.

Syntax:**limit_req_zone** *key* zone=*name*:*size* rate=*rate* [sync];
Default:
Context:http

Sets parameters for a shared memory zone that will keep states for various keys. In particular, the state stores the current number of excessive requests. The *key* can contain text, variables, and their combination. Requests with an empty key value are not accounted.

Prior to version 1.7.6, a *key* could contain exactly one variable.

Usage example:

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

Here, the states are kept in a 10 megabyte zone “one”, and an average request processing rate for this zone cannot exceed 1 request per second.

A client IP address serves as a key. Note that instead of $remote_addr, the $binary_remote_addr variable is used here. The $binary_remote_addr variable’s size is always 4 bytes for IPv4 addresses or 16 bytes for IPv6 addresses. The stored state always occupies 64 bytes on 32-bit platforms and 128 bytes on 64-bit platforms. One megabyte zone can keep about 16 thousand 64-byte states or about 8 thousand 128-byte states.

If the zone storage is exhausted, the least recently used state is removed. Even if after that a new state cannot be created, the request is terminated with an error.

The rate is specified in requests per second (r/s). If a rate of less than one request per second is desired, it is specified in request per minute (r/m). For example, half-request per second is 30r/m.

The sync parameter (1.15.3) enables synchronization of the shared memory zone.

The sync parameter is available as part of our commercial subscription.

test case

修改default.conf文件,添加相关的配置

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
    listen       80;
    server_name  localhost;
    location / {
         #limit_req zone=one burst=5 nodelay;
         #limit_req zone=one burst=5;
         limit_req zone=one;
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
#使用apache bench 工具测试
ab -n 20 -c 20 http://127.0.0.1/website.html

在上面的配置中,配置了rate=1r/s,所以一秒只能一个请求,所以当我们使用上面的命令测试时,只会有一条通过,还有19条error log,可通过查看error日志的方式去查看相应的信息。

使用 limit_req zone=one burst=5 nodelay;时,会有5个请求放在下一秒执行,剩下十五个请求在这一秒执行,执行测试,查看error日志,有6个请求是成功的,原因是这一秒有一个请求是成功的,还有五个是延迟请求。当然也可以通过查看ab工具显示在屏幕的日志。

ngx_http_access_module

The ngx_http_access_module module allows limiting access to certain client addresses.

Access can also be limited by password, by the result of subrequest, or by JWT. Simultaneous limitation of access by address and by password is controlled by the satisfy directive.

Example Configuration
location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

The rules are checked in sequence until the first match is found. In this example, access is allowed only for IPv4 networks 10.1.1.0/16 and 192.168.1.0/24 excluding the address 192.168.1.1, and for IPv6 network 2001:0db8::/32. In case of a lot of rules, the use of the ngx_http_geo_module module variables is preferable.

Directives
Syntax:**allow** *address* | *CIDR* | unix: | all;
Default:
Context:http, server, location, limit_except

Allows access for the specified network or address. If the special value unix: is specified (1.5.1), allows access for all UNIX-domain sockets.

Syntax:**deny** *address* | *CIDR* | unix: | all;
Default:
Context:http, server, location, limit_except

Denies access for the specified network or address. If the special value unix: is specified (1.5.1), denies access for all UNIX-domain sockets.

test case

在nginx 的default.conf文件中配置相应的访问控制

server {
    listen       80;
    server_name  localhost;
    location / {
        deny 127.0.0.1; #不允许本机访问
        allow 182.149.166.54; #允许远程的某个ip访问
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

当我使用上面的配置文件时,使用本机访问会出现403错误,这是因为没有权限导致的,而远程的主机却能直接访问。

ngx_http_auth_basic_module

The ngx_http_auth_basic_module module allows limiting access to resources by validating the user name and password using the “HTTP Basic Authentication” protocol.

Access can also be limited by address, by the result of subrequest, or by JWT. Simultaneous limitation of access by address and by password is controlled by the satisfy directive.

Example Configuration
location / {
    auth_basic           "closed site";
    auth_basic_user_file conf/htpasswd;
}
Directives
Syntax:**auth_basic** *string* | off;
Default:auth_basic off;
Context:http, server, location, limit_except

Enables validation of user name and password using the “HTTP Basic Authentication” protocol. The specified parameter is used as a *realm*. Parameter value can contain variables (1.3.10, 1.2.7). The special value offallows cancelling the effect of the auth_basic directive inherited from the previous configuration level.

Syntax:**auth_basic_user_file** *file*;
Default:
Context:http, server, location, limit_except

Specifies a file that keeps user names and passwords, in the following format:

# comment
name1:password1
name2:password2:comment
name3:password3

The *file* name can contain variables.

The following password types are supported:

  • encrypted with the crypt() function; can be generated using the “htpasswd” utility from the Apache HTTP Server distribution or the “openssl passwd” command;

  • hashed with the Apache variant of the MD5-based password algorithm (apr1); can be generated with the same tools;

  • specified by the “{scheme}data” syntax (1.0.3+) as described in RFC 2307; currently implemented schemes include PLAIN(an example one, should not be used),SHA(1.3.13) (plain SHA-1 hashing, should not be used) and SSHA(salted SHA-1 hashing, used by some software packages, notably OpenLDAP and Dovecot).

    Support for SHA scheme was added only to aid in migration from other web servers. It should not be used for new passwords, since unsalted SHA-1 hashing that it employs is vulnerable to rainbow tableattacks.

test case

修改default.conf

server {
    listen       80;
    server_name  localhost;
    location / {
        auth_basic   "Nginx认证";
        auth_basic_user_file conf.d/htpasswd; # 配置文件位置,该位置是相对于/etc/nginx目录
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}


#添加认证文件,生成用户名为admin,密码为admin的用户,该htpasswd文件应该跟default.conf在一个目录
htpasswd -bdc htpasswd admin admin
#同样可以使用openssl生成密码,然后将密码写到htpasswd文件中
openssl passwd admin

使用本机访问测试

curl -u admin:admin 127.0.0.1 # 将返回相应的nginx信息

或者直接使用浏览器访问,此时会提示输入用户名和密码

ngx_http_gzip_module

The ngx_http_gzip_module module is a filter that compresses responses using the “gzip” method. This often helps to reduce the size of transmitted data by half or even more.

When using the SSL/TLS protocol, compressed responses may be subject to BREACH attacks.

Example Configuration
gzip            on;
gzip_min_length 1000;
gzip_proxied    expired no-cache no-store private auth;
gzip_types      text/plain application/xml;

The $gzip_ratio variable can be used to log the achieved compression ratio.

Directives
Syntax:**gzip** on | off;
Default:gzip off;
Context:http, server, location, if in location

Enables or disables gzipping of responses.

Syntax:**gzip_buffers** *number* *size*;
Default:gzip_buffers 32 4k|16 8k;
Context:http, server, location

Sets the *number* and *size* of buffers used to compress a response. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform.

Until version 0.7.28, four 4K or 8K buffers were used by default.

Syntax:**gzip_comp_level** *level*;
Default:gzip_comp_level 1;
Context:http, server, location

Sets a gzip compression *level* of a response. Acceptable values are in the range from 1 to 9.

Syntax:**gzip_disable** *regex* ...;
Default:
Context:http, server, location

This directive appeared in version 0.6.23.

Disables gzipping of responses for requests with “User-Agent” header fields matching any of the specified regular expressions.

The special mask “msie6” (0.7.12) corresponds to the regular expression “MSIE [4-6]\.”, but works faster. Starting from version 0.8.11, “MSIE 6.0; ... SV1” is excluded from this mask.

Syntax:**gzip_http_version** 1.0 | 1.1;
Default:gzip_http_version 1.1;
Context:http, server, location

Sets the minimum HTTP version of a request required to compress a response.

Syntax:**gzip_min_length** *length*;
Default:gzip_min_length 20;
Context:http, server, location

Sets the minimum length of a response that will be gzipped. The length is determined only from the “Content-Length” response header field.

Syntax:**gzip_proxied** off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth |any ...;
Default:gzip_proxied off;
Context:http, server, location

Enables or disables gzipping of responses for proxied requests depending on the request and response. The fact that the request is proxied is determined by the presence of the “Via” request header field. The directive accepts multiple parameters:

  • off

    disables compression for all proxied requests, ignoring other parameters;

  • expired

    enables compression if a response header includes the “Expires” field with a value that disables caching;

  • no-cache

    enables compression if a response header includes the “Cache-Control” field with the “no-cache” parameter;

  • no-store

    enables compression if a response header includes the “Cache-Control” field with the “no-store” parameter;

  • private

    enables compression if a response header includes the “Cache-Control” field with the “private” parameter;

  • no_last_modified

    enables compression if a response header does not include the “Last-Modified” field;

  • no_etag

    enables compression if a response header does not include the “ETag” field;

  • auth

    enables compression if a request header includes the “Authorization” field;

  • any

    enables compression for all proxied requests.

Syntax:**gzip_types** *mime-type* ...;
Default:gzip_types text/html;
Context:http, server, location

Enables gzipping of responses for the specified MIME types in addition to “text/html”. The special value “*” matches any MIME type (0.8.29). Responses with the “text/html” type are always compressed.

Syntax:**gzip_vary** on | off;
Default:gzip_vary off;
Context:http, server, location

Enables or disables inserting the “Vary: Accept-Encoding” response header field if the directives gzip,gzip_static, or gunzip are active.

Embedded Variables
  • $gzip_ratio

    achieved compression ratio, computed as the ratio between the original and compressed response sizes.

ngx_http_gzip_static_module

The ngx_http_gzip_static_module module allows sending precompressed files with the “.gz” filename extension instead of regular files.

This module is not built by default, it should be enabled with the --with-http_gzip_static_module configuration parameter.

Example Configuration
gzip_static  on;
gzip_proxied expired no-cache no-store private auth;
Directives
Syntax:**gzip_static** on | off | always;
Default:gzip_static off;
Context:http, server, location

Enables (“on”) or disables (“off”) checking the existence of precompressed files. The following directives are also taken into account: gzip_http_version, gzip_proxied, gzip_disable, and gzip_vary.

With the “always” value (1.3.6), gzipped file is used in all cases, without checking if the client supports it. It is useful if there are no uncompressed files on the disk anyway or the ngx_http_gunzip_module is used.

The files can be compressed using the gzip command, or any other compatible one. It is recommended that the modification date and time of original and compressed files be the same.

ngx_http_gunzip_module

The ngx_http_gunzip_module module is a filter that decompresses responses with “Content-Encoding: gzip” for clients that do not support “gzip” encoding method. The module will be useful when it is desirable to store data compressed to save space and reduce I/O costs.

This module is not built by default, it should be enabled with the --with-http_gunzip_module configuration parameter.

Example Configuration
location /storage/ {
    gunzip on;
    ...
}
Directives
Syntax:**gunzip** on | off;
Default:gunzip off;
Context:http, server, location

Enables or disables decompression of gzipped responses for clients that lack gzip support. If enabled, the following directives are also taken into account when determining if clients support gzip: gzip_http_version,gzip_proxied, and gzip_disable. See also the gzip_vary directive.

Syntax:**gunzip_buffers** *number* *size*;
Default:gunzip_buffers 32 4k|16 8k;
Context:http, server, location

Sets the *number* and *size* of buffers used to decompress a response. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform.

ngx_http_referer_module

The ngx_http_referer_module module is used to block access to a site for requests with invalid values in the “Referer” header field. It should be kept in mind that fabricating a request with an appropriate “Referer” field value is quite easy, and so the intended purpose of this module is not to block such requests thoroughly but to block the mass flow of requests sent by regular browsers. It should also be taken into consideration that regular browsers may not send the “Referer” field even for valid requests.

Example Configuration
valid_referers none blocked server_names
               *.example.com example.* www.example.org/galleries/
               ~\.google\.;

if ($invalid_referer) {
    return 403;
}
Directives
Syntax:**referer_hash_bucket_size** *size*;
Default:referer_hash_bucket_size 64;
Context:server, location

This directive appeared in version 1.0.5.

Sets the bucket size for the valid referers hash tables. The details of setting up hash tables are provided in a separate document.

Syntax:**referer_hash_max_size** *size*;
Default:referer_hash_max_size 2048;
Context:server, location

This directive appeared in version 1.0.5.

Sets the maximum *size* of the valid referers hash tables. The details of setting up hash tables are provided in a separate document.

Syntax:**valid_referers** none | blocked | server_names | *string* ...;
Default:
Context:server, location

Specifies the “Referer” request header field values that will cause the embedded $invalid_referer variable to be set to an empty string. Otherwise, the variable will be set to “1”. Search for a match is case-insensitive.

Parameters can be as follows:

  • none

    the “Referer” field is missing in the request header;

  • blocked

    the “Referer” field is present in the request header, but its value has been deleted by a firewall or proxy server; such values are strings that do not start with “http://” or “https://”;

  • server_names

    the “Referer” request header field contains one of the server names;

  • arbitrary string

    defines a server name and an optional URI prefix. A server name can have an “*” at the beginning or end. During the checking, the server’s port in the “Referer” field is ignored;

  • regular expression

    the first symbol should be a “~”. It should be noted that an expression will be matched against the text starting after the “http://” or “https://”.

Example:

valid_referers none blocked server_names
               *.example.com example.* www.example.org/galleries/
               ~\.google\.;
Embedded Variables
  • $invalid_referer

    Empty string, if the “Referer” request header field value is considered valid, otherwise “1”.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值