This paper is to sort out the Nginx based system of an article, the original links: docs.chenfangxu.com/server/ngin…

The global variable

Nginx has some common global variables that can be used anywhere in the configuration. To name some of the more common ones:

variable describe
HTTP related variables
$host Host in the request line, if there is a Host header, replaces the Host name in the request line with its value, if there is no Host line and Host header, is equal to the name of the server matching the request (the value of the server_name directive processing the request server), The value is lowercase and does not contain ports
$uri The current URI in the request (unlike the URL, does not include?The request parameter, which follows, is located$args), different from browser delivery$request_uri, which can be modified by internal redirection or using the index directive, excluding protocol and host names, such as/ABC /ef.html
$document_uri The value specified in the root directive for the current request, and$uriExactly the same, historical problems exist
$request_uri The complete original request URL (including URI and full parameters), which cannot be modified, please see$uriChange or rewrite the URL
$scheme Request mode, HTTP or HTTPS
$request The original URL request with the method and protocol version, such as GET /? A = 1 & b = 22 HTTP / 1.1
$request_method Client request type, such as GET or POST
$request_length The size of all request content, including request lines, headers, package bodies, and so on
$request_body Package body in the request. This variable is valid if and only if a reverse proxy is used and if the package body is set to memory staging
$request_body_file Client_body_in_file_only can be used to force all packages to be stored and delete them
$remote_user User name passed through HTTP Basic Authentication
$args Parameter in the request, this variable can be modified
$arg_PARAMETER PARAMETER specifies the value of the variable name PARAMETER in the GET request./test? name=abc.$arg_nameFor ABC
$is_args “?” if the request has parameters. Otherwise, empty string “”
$query_string with$argsThe same
$content_length Content-length field in the request header that identifies the packet body Length
$content_type The Content-Type field in the request header that identifies the package Type
$http_HEADER The content in the HTTP request HEADER. HEADER is the content in the HTTP request converted to lowercase and – changed to _ (dashes changed to underscores), for example$http_user_agent
$http_user_agent Client Agent information
$http_cookie Client cookie information
$cookie_COOKIE with$arg_PARAMETERSimilarly, get a cookie value
Variables related to TCP connections
$binary_remote_addr The client address is an integer of 4 bytes for IPv4 and 16 bytes for IPv6
$remote_addr IP address of the client
$remote_port Client port
$connection Increasing connection number
$connection_requests The number of requests executed on the current connection, which is meaningful for keepalive connections
$proxy_protocol_addr If proxy_protocol is used, the address in the protocol (original user address) is returned; otherwise, nothing is returned
$proxy_protocol_port If proxy_protocol is used, the port in the protocol (the original user’s port) is returned; otherwise, nothing is returned
$server_addr Server address
$server_port Server port
$server_protocol Server-side protocols, such as HTTP/1.1
$TCP_INFO TCP kernel layer parameters, including$tcpinfo_rtt,$tcpinfo_rttvar,$tcpinfo_snd_cwnd,$tcpinfo_rcv_space
Nginx handles variables generated during a request
$request_time The elapsed time of the request processing to date, in seconds to milliseconds
$server_name Matches the requested server_name value
$https Return on if TLS/SSL is enabled, null otherwise
$request_completion Return OK if the request is finished, null otherwise
$request_id The request id, printed in hexadecimal, is randomly generated and contains 16 bytes
$request_filename Full path of the file to be accessed
$document_root The folder path generated by the URI and root/alias rules
$realpath_root Replace soft links and so on in document_root with real paths
$limit_rate Returns the speed at which the client responds to go online, in bytes per second. Can be achieved bysetInstruction modification has an effect on the request
Variables that are relevant when sending the HTTP response
$sent_http_HEADER The content in the HTTP response HEADER. HEADER is the content in the HTTP response. The content is lowercase and the – is changed to _ (dashes are changed to underscores), for example$sent_http_cache_controlsent_http_content_type
$status HTTP Response Status
$body_bytes_sent The number of bytes sent to the page, which is the length of the body package in the response
$bytes_sent The length of the total HTTP response
$sent_trailer_ name Returns the value at the end of the response
Nginx system variable
$time_local Current time in local time standard output
$time_iso8601 The current time using ISO 8601 standard output
$nginx_version The version number of Nginx currently running
$pid Worker ID of the owning process
$pipe P is returned if a pipe is used, otherwise.
$hostname The hostname of the server is the same as the hostname command output
$msec Time from January 1, 1970 to the present, in seconds, accurate to the millisecond after the decimal point

How does Nginx set variables

Nginx configuration files use a tiny programming language. As a programming language, there is always such a thing as “variables”, but in Nginx configuration, variables can only hold one type of value, which is a string.

Variable values can be dynamically specified using the set configuration directive, Nginx variable names are preceded by a $sign, and all Nginx variables must be prefixed with a $prefix when referenced in Nginx configuration files

set $limit_rate 1K; Limit the response transfer rate to the client.
Copy the code

When referencing a variable, note that when the variable name is followed by a character (such as a letter, number, or underscore), special syntax is used to disambiguate:

server {
  listen 80;
  server_name test.com;

  set $temp hello;

  location / {
    default_type text/html;
    return 200 "$temp world";
  }

  location /close {
    default_type text/html;
    return 200 "${hello}world"; # follow the character}}Copy the code

Note also that if you want to print the $symbol itself, you can do this:

geo $dollar {
  default "$";
}

server {
  listen 80;
  server_name test.com;

  location {
    set $temp "hello ";
    default_type text/html;
    return 200 "${temp}World: $dollar."; }}Copy the code

${dollar} returns hello World: $using the ngx_geo configuration directive to assign the string “$” to the variable ${dollar}

Nginx variable implementation principle

The corresponding modules of Nginx variables can be divided into: variable supply module and variable use module

  • When Nginx starts, the module that provides variables can define new variables in preConfiguration, including defining variable names and separating variable methods
  • After the HTTP header is read, modules that use variables, such as HTTP access logs, define how to use variables when parsing nginx.conf, and obtain values from the corresponding method of parsing variables when processing requests

The Map module provides more possibilities by mapping new variables

The map module can be based on existing variables, using something like switch {case:… default … } syntax to create new variables, opening up more possibilities for other modules that implement functions based on variable values. Ngx_http_map_module is the default build feed.

The map instruction

Map string $variable {… }, can only be used in HTTP context.

  • stringAn existing variable can be a string, one or more variables, or a combination of variables and strings
  • $variableNew variables generated
  • Case rules (priority from high to low)
    • Strict string matching
    • Using the HostNames directive, you can prefix domain names*Generic domain name matching
    • Using the hostNames directive, you can assign a suffix to a domain name*Generic domain name matching
    • ~~ *Regular expression matches, which ignores case
  • The default rules
    • If no rule is matched, use default
    • Missing default returns an empty string to the new variable, that is, false
  • Other situations
    • Use include syntax to improve readability
    • Use volatile to disallow variable value caching
map $http_host $name {
  hostnames;

  default 0;

  ~map\.x\w+\.org.cn 1;
  *.xu.org.cn 2;
  map.xu.tech 3;
  map.xu.* 4;
}
Copy the code

For example, request header Host: map.xu.org.cn generic domain name matching takes precedence over regular matching, so $name is 2.

Split_client module specifies variables for a small number of users (AB tests can be implemented)

The module compiles into Nginx by default and creates new variables based on existing variables (existing variables can be strings, one or more variables, and combinations of variables and strings).

Process:

  • The MurmurHash2 algorithm is performed on the value of an existing variable to produce a 32-bit integer hash number, denoted as hash
  • The maximum number of a 32-bit unsigned integer is 2^32-1, denoted as Max
  • Hash/Max gives you percent
  • The configuration instruction indicates the range of each percentage, such as 0-1%,1%-5%, and the corresponding value of the range
  • When percent falls in any range, the value of the new variable corresponds to the following parameter.

Rules of the case

  • Xx. Xx % The percentage of all items cannot exceed 100%
  • *It matches the remaining percentage (100% minus the percentage of all the above items added up)
split_clients "${http_testcli}"$variant {0.51%. One; 20.0% in tow; * ""; }Copy the code

The GEO module generates new variables based on IP address ranges

$variable {geo [$address] $variable {… }, create a new variable based on the IP address, compiled into Nginx by default. Can only be used in HTTP context.

  • If the geo directive is not followed by address, then address is used by default, then address is used by default, and then the remote_ADDR variable is used as the IP address by default
  • Instruction matching in {} : priority longest matching
    • The IP address range is defined by IP address and subnet mask. If the IP address is in the range, the new variable uses the following parameter value
    • Default specifies the default value for the new variable if none of the above ranges are matched
    • If the proxy specifies a new IP address, remote_ADDR is the last IP address in the x-Forwarded-For header
    • Include optimizes readability
    • Delete Deletes the specified network
geo $country {
  default ZZ;

  #include conf/geo.conf;
  proxy 116.62.160.193;

  127.0.0.0/24 US;
  127.0.0.1/32 RU;
  10.1.0.0/16 RU;
  192.168.1.0 UK;
}
Copy the code

The basic structure of Nginx configuration files

Get compiled before we install Nginx main configuration file/usr/local/Nginx/conf/Nginx. Conf, Nginx. Roughly the conf’s structure is as follows:

main        The global configuration of Nginx takes effect globally├ ─ ─ eventsThe configuration affects the nginx server or network connection to the user├ ─ ─ HTTPConfigure proxy, cache, log definition and most of the functions and third-party module configuration, can nest multiple servers│ ├ ─ ─ upstreamConfigure the back-end server specific address, load balancing configuration indispensable part│ ├ ─ ─ server# Configure the parameters of the virtual host, such as domain name, IP, port, etc., one HTTP block can have multiple server blocks│ ├─ Server │ ├─ LocationConfigure the routing of requests and the processing of various pages│ │ ├ ─ ─ the locationThe server block can contain multiple location blocks. The location directive is used to match urIs│ │ └ ─ ─... │ └ ─ ─... └ ─ ─...Copy the code

Syntax rules for Nginx configuration files

Nginx is made up of modules, usually controlled by specific instructions in configuration files. Instructions are divided into simple instructions (referred to as instructions) and block level instructions (referred to as instruction blocks).

Simple instructions

Simple instructions consist of names and arguments separated by Spaces and terminated with a semicolon.

# Simple instructions
root /data/www;
Copy the code

Block-level instruction

Block-level instructions have a similar structure to simple instructions, but instead of ending with a semicolon, they are an extra set of instructions wrapped in braces ({}). If a block-level directive has other directives in braces, it is called a context (for example: Events, HTTP, Server, and Location).

In a configuration file, instructions that are not placed in any context are placed in the main context. Events and HTTP directives are placed on the main context, server is placed on HTTP, and Location is placed on server.

# block-level instructions
http {
  server {
    listen 80;
    server_name doc.chenfangxu.com;
    access_log logs/doc.chenfangxu.access.log;
    root html;

    location ~ \.php$ {
      fastcgi_pass 127.0.0.1:1025; }}}Copy the code

Grammar rules

  • Configuration files are made up of instructions and instruction blocks
  • Each instruction is preceded by a semicolon (;), instructions and parameters are separated by a space symbol
  • The instruction block is wrapped in braces ({}Group multiple instructions together
  • includeStatement allows multiple configuration files to be combined to improve maintainability
  • through#Symbols add comments to improve maintainability
  • through$Symbol use variable
  • Some directives have arguments that support regular expressions, such as the commonly used Location directive

Location directive rule

The location directive is used to match only URIs, ignoring arguments, using either a valid string or a regular expression

Grammar:

location[= |~ | ~ * |^ ~| empty] uri {... }Copy the code

After the instruction:

  • =: Exact match. It is used before a URI that does not contain a regular expression. If the match is successful, no further search is performed
  • ^ ~: prefix match, used before a URI that does not contain a regular expression, if the character following the symbol is the best match. With this rule, no further re lookups are performed. with=The difference is that the URI does not need to be identical, only the beginning needs to match the URI.
  • ~: Indicates that a path is matched using the regular URI following the symbol. It is case sensitive
  • ~ *: Indicates that a path is matched using the regular URI following the symbol, which is case insensitive.
  • empty: Ordinary match (longest character match), matches a string that starts with a URI. For example,location /It is a generic match, and any request will be matched. In addition, ordinary matching has nothing to do with the order of location, but determines the matching result according to the length of the match.

priority

Location = > location ^~ path > location ~,~* regular order > location partial start path > location /

That is: Exact match > longest string match, full match (but also to match re) > Prefix match > Regular match > Normal match (longest string match, partial match) > general match

Note:

  • Among all urIs that are successfully matched, the URI character address with the longest matching degree is selected. With the exception of re, re matching determines the matching results in sequence
  • After a regular match is successful, the match stops. After a regular match is successful, the match continues. Here’s an example:
# 'location full path' has a higher priority than 'location ^~ path', but it will still match the re
If the regex match succeeds, the result of the regex match is adopted. If no location full path is matched, the location ^~ path takes precedence over the location ~,~* regular order
location ~ /ab {
  rewrite ^ http://baidu.com/s?word=A;
}
location /abc {
  rewrite ^ http://baidu.com/s?word=B;
}
location^ ~ /ab {
  rewrite ^ http://baidu.com/s?word=C;
}

# visit http://docs.chenfangxu.com/ab C jump to baidu search keywords
# visit http://docs.chenfangxu.com/abc jump to A baidu search keywords
Copy the code
  • If the URI contains a regular expression, it must~~ *Flag, otherwise the re code can only be used as normal characters, for examplelocation = /demo$, in which the$Does not mean the end of the regular pattern, but a real one$Character is part of the URL.
  • for~~ *Match identifier, which can be preceded!To take the:! ~: indicates that the re does not match and is case sensitive.! ~ *: indicates that the re is not matched and is case insensitive

Simulate the matching process of Nginx location based on priority

  1. Nginx first checks the longest matching prefix string based on the URL=,^ ~,emptyThe content defined by the modifier
  • If you match the longest matching prefix string (that is, the longest URI)
    • If the longest match prefix string is=If the modifier matches, thenRespond immediately
    • If not by=If the modifier matches, step 2 is performed.
  • If the longest match prefix string is not matched
  1. Nginx continues to check for the longest matching prefix string, called judgment^ ~,emptyThe content defined by the modifier
  • If the longest match prefix string is^ ~If the modifier matches, thenRespond immediately
  • If you areemptyIf the modifier matches, thenSave the match(whether a normal match is a full match or a partial match), and perform step 3.
  1. Nginx finds all regular matches defined in nginx.conf (~and~ *) and match in order.
  • If any regular expression matches successfully, the response is immediate
  • If no re matches are successful, the result of the null modifier match stored in step 2 is responded.

Loaction other

  1. @It starts with the name location for the internal jump.
  2. Merge_slashes can merge repeated slashes in urls, which need to be turned on in all cases except base64 encoding

A typical configuration

Source code compiled to install/usr/local/nginxTypical configuration of Nginx

#user nobody; # define the user and user group for Nginx to run. Default is nobody account
worker_processes  1;  # Number of Nginx processes, usually set to the same as the number of CPU cores

# Nginx error log directory, can be followed by the log type
Global error log # define types include: [the debug | info | notice | warn | error | crit]
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid; Nginx service startup PID storage location


events {
    # reference event model, use [kqueue | rtsig | epoll | / dev/poll | select | poll];
    The # epoll model is a high-performance network I/O model in the Linux 2.6 or higher kernel. If running on FreeBSD, the kqueue model is used.
    #use epoll;
    worker_connections  1024; # Maximum number of concurrent requests per process
}


http {  Configure the most frequently used parts, proxy, cache, log definition and most of the functions and third-party module configuration are set here
    # include is a main module directive that can split and reference the configuration file, reducing the complexity of the main configuration file
    include       mime.types; File extension and type mapping table
    default_type  application/octet-stream; The default file type

    Set the log 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 logs/access.log main; # Nginx access log location

    sendfile        on; Enable efficient transmission mode
    #tcp_nopush on; # Reduce the number of network packet segments to prevent network congestion
    #autoindex on; # Enable directory list access, suitable for downloading servers

    #keepalive_timeout 0;
    keepalive_timeout  65;  # Timeout duration, also called timeout duration, in seconds. Default is 0

    #gzip on;

    include	/usr/local/nginx/conf/conf.d/*.conf; Load subconfiguration items

    server {  Configure virtual host parameters, such as domain name, IP address, port number, etc
        listen       80;  Configure the listening port
        server_name  localhost; Use Spaces to separate multiple domain names

        #charset koi8-r; # default encoding

        #access_log logs/host.access.log main; # Define the access log for this VM

        location / {
            root   html;  # site root directory
            index  index.html index.htm;  # Default home page file
        }

        #error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;  # Default 50x corresponding access page
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        # proxy_pass http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        # root html;
        # fastcgi_pass 127.0.0.1:9000;
        # fastcgi_index index.php;
        # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
        # include fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        # deny all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    # listen 8000;
    # listen somename:8080;
    # server_name somename alias another.alias;

    # location / {
    # root html;
    # index index.html index.htm;
    #}
    #}


    # HTTPS server
    #
    #server {
    # listen 443 ssl;
    # server_name localhost;

    # ssl_certificate cert.pem;
    # ssl_certificate_key cert.key;

    # ssl_session_cache shared:SSL:1m;
    # ssl_session_timeout 5m;

    # ssl_ciphers HIGH:! aNULL:! MD5;
    # ssl_prefer_server_ciphers on;

    # location / {
    # root html;
    # index index.html index.htm;
    #}
    #}

}
Copy the code

Typical configuration of Nginx for yum installation

user  nginx;                        # run user
worker_processes  1;                # Number of Nginx processes, usually set to the same as the number of CPU cores
error_log  /var/log/nginx/error.log warn;   # Nginx error log directory
pid        /var/run/nginx.pid;      # Nginx pid location when the service is started

events {
    use epoll;     # Use epoll's I/O model (if you don't know which polling method Nginx should use, it will automatically choose the one that is best for your operating system)
    worker_connections 1024;   # Maximum number of concurrent requests per process
}

http {   Configure the most frequently used part, proxy, cache, log definition and most of the functions and third-party module configuration are set here
    Set the logging mode
    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;   # Nginx access log location

    sendfile            on;   Enable efficient transmission mode
    tcp_nopush          on;   # Reduce the number of network packet segments
    tcp_nodelay         on;
    keepalive_timeout   65;   # Time to hold a connection, also called timeout, in seconds
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;      File extension and type mapping table
    default_type        application/octet-stream;   The default file type

    include /etc/nginx/conf.d/*.conf;   Load subconfiguration items

    server {
    	listen       80;       Configure the listening port
    	server_name  localhost;    # Configure the domain name

    	location / {
    		root   /usr/share/nginx/html;  # site root directory
    		index  index.html index.htm;   # Default home page file
    		deny 172.168.22.11;   The IP address can be all
    		allow 172.168.33.44;The allowed IP address can be all
    	}

    	error_page 500 502 503 504 /50x.html;  # Default 50x corresponding access page
    	error_page 400 404 error.html;   # same as above}}Copy the code

Description of common commands in configuration

Instruction is introduced

Directives have a Context, and different directives may have different contexts to apply.

  • Value directives mainly store the values of configuration items. Value directives can be combined, and the inheritance rule is upward overwriting. That is, if the child configuration does not exist, the parent configuration is directly used, and if the child configuration does exist, the parent configuration is directly overwritten. For example,root,access_log,gzipSuch as instruction
  • Action instructions, which specify actions, cannot be combined, for examplerewrite,proxy_passAnd so on. The effective stage of these instructions is generallyServer_rewrite phase,Rewrite phase,The content stage.

Main Global configuration

  • worker_processes 1;

Defines the number of worker processes for the worker role in the top-level main section of the profile. The master process accepts and allocates the request to the worker. This value can be set to simple CPU auditing grep ^ processor/proc/cpuinfo | wc -l, also can be auto. If SSL and Gzip are enabled, the number of logical cpus should be set to the same or even twice as many to reduce I/O operations. If the Nginx server has other services, consider reducing them appropriately.

  • worker_cpu_affinity 0001 0010 0100 1000;

Defined in the main section. In the case of high concurrency, the performance loss caused by register reconstruction due to multi-CPU core switching can be reduced by setting CPU stickiness. Worker_cpu_affinity 0001 0010 0100 1000; (Quad-core).

  • use epoll;Put it in the Events section. Because nginx uses the epoll event model by default on Linux, nginx is quite efficient on Linux. Meanwhile, Nginx uses an efficient event model kQueue similar to EPoll on OpenBSD or FreeBSD operating systems. Use SELECT only when the operating system does not support these efficient models.

The HTTP configuration

  • sendfile on;

    With efficient transfer mode enabled, the sendFile directive specifies whether nginx calls the sendfile function to output files, reducing context switching from user space to kernel space. Set this parameter to ON for common applications. Set this parameter to off for heavy disk I/O load applications, such as downloads, to balance disk AND network I/O processing speeds and reduce system load. Note: Change this to off if the image does not display properly.

  • client_max_body_size 10m;

    Maximum number of bytes per file that a client is allowed to request. If a large file is uploaded, set its limit value.

Server virtual host

Several virtual hosts are supported on HTTP services. Each virtual host corresponds to a server configuration item, which contains the configuration of the virtual host. When providing the proxy of mail service, several servers can also be established, and each server can be distinguished by listening for address or port.

  • listen 80;

    The default value is 80. If the value is smaller than 1024, start as root. You can specify only the port or the address and port. , listen 127.0.0.1:80

  • server_name localhost;

    You can set multiple server names. The first name becomes the name of the primary server (the primary domain name). The first or last part of the server name can be replaced by *. You can also use regular matching (prefixed with ~), or you can use regular expressions to capture.

    server {
      server_name example.com *.example.com www.example.*;
    }
    Copy the code

Server_name extension

1. Server_name Using the first name as the primary domain name works with the server_name_in_redirect to redirect multiple subdomain names to the primary domain name.

Serve_name can create variables using regular expression parentheses () and Angle parentheses. <> to name variables.

# Use the re, and create variables
server {
  server_name~^(www\.) ? (. +) $;location / {
      root /sites/$2; }}Create a named variable
server {
  server_name~^(www\.) ? (? <domain>.+)$;location / {
      root/sites/$domain; }}Copy the code

3.. Example.com can match example.com *. Example.com

4. _ Matches all domain names

Server_name in a server block uses “” to match requests that do not pass the Host header

Matching order of multiple server blocks

  1. Nginx.conf takes precedence over exact matching, regardless of the order in which server blocks are placed
  2. Second preference matching*In front of the pan-domain
  3. Second preference matching*After the generic domain name
  4. The next step is to match the regular expression domain names in the order they appear in the nginx.conf file
  5. The default server is divided into two cases. The first case is matching the first server block, and the other case is iflistenThe instruction followsdefault, the server block is the Default Server.

localtion

Allow /deny Access control

Nginx access control module will be installed by default, and simple writing, can be multiple allow/deny, allow or deny a certain IP address or IP segment access, meet any rule in turn stop matching.

location /nginx-status {

  allow 192.168.10.100;
  allow 172.29.73.0/24;
  deny all;
}
Copy the code

We also use the httpd-devel tool htpasswd to set the login password for the access path :(I did not verify here)

htpasswd -c htpasswd admin New passwd: Re-type new password: Adding password for user admin htpasswd htpasswd admin // Change the admin password htpasswd htpasswd Sean // Add another authentication userCopy the code
location /nginx-status {
  # auth_basic "NginxStatus";
  #  auth_basic_user_file   /usr/local/nginx-1.6/htpasswd;

  allow 192.168.10.100;
  allow 172.29.73.0/24;
  deny all;
}
Copy the code

This generates a password file that is encrypted with CRYPT by default. Open the two lines of comment above for nginx-status and restart nginx to take effect.

Lists the directory autoindex

Nginx does not allow listing entire directories by default. If you need this feature, open the nginx.conf file and add autoindex on to the location, server, or HTTP section; The other two parameters had better be added as well:

  • autoindex_exact_size off;

    The default is on, which displays the exact size of the file in bytes. When changed to off, the approximate size of the file is displayed in KB, MB, or GB.

  • autoindex_localtime on;

    The default value is off, and the displayed file time is GMT. After the file time is changed to ON, the file server time is displayed.

location /images {
  root   /var/www/nginx-default/images;
  autoindex on;
  autoindex_exact_size off;
  autoindex_localtime on;
}
Copy the code

Nginx if judgment

If (condition) {... }Copy the code

Rewrite, provided by the rewrite module, can be used in server,location contexts to execute the instructions in braces if the condition is true; Follow the inheritance rules of value instructions

Expression syntax in parentheses

Common grammar

  • When the expression is just a variable, it is treated if the value is null or if any string begins with 0false
  • To directly compare variables and content, use = or! =
if($request_method ! = POST) {return 405;
}
Copy the code

Regular grammar

  • ~! ~Determines whether a regular expression is matched and is case sensitive
  • ~ *! ~ *Determines whether a regular expression is matched, case insensitive
# if id=1 then 301 to the specified domain
if ($args ~ id=1) {
  rewrite ^ http://example.com permanent;
}
Copy the code
location = /test.html {
  set $name aaa;
  # if name= XXX, use this value
  if($args ~* name=(\w+?) (& | $)) {
    set $name The $1;
  }

  # 301 jump
  rewrite ^ /$name.html permanent;
  # /test.html => /aaa.html
  # /test.html? name=bbb => /bbb.html
}
Copy the code

Documents and Contents

  • -f! -fDetermine whether files exist
  • -d! -dCheck whether a directory exists
  • -e! -eCheck whether files, directories, and soft connections exist
  • -x! -xDetermines whether the file is executable
if(! -f $request_filename) {return 400;
}
Copy the code

The cause of the problem with the if command

  • The if directive executes in the rewrite phase
  • The configuration in the if {} block replaces the currently requested configuration when the if condition is true
    • If {} also inherits the parent configuration up
    • When executed sequentially in the rewrite phase, each time an if is true it replaces the current requested configuration (successive ifs overwrite previous ones)
  • Configurations in if {} affect phase execution after the rewrite phase

Error_page configuration

The syntax of the error_page directive is error_page code… [=[response]] uri; , the context you can use is HTTP,server,location,if in location.

Example:

  1. error_page 404 /404.html;
  2. error_page 500 502 503 504 /50x.html;
  3. error_page 404 =200 /empty.gifReplace the 404 status code with 200 and return it to the client
  4. error_page 404 = /404.php;
  5. error_page 403 http://example.com/forbidden.html
  6. error_page 404 =301 http://example.com/notfound.html
  7. Internal jump based on @ sign
location / {
  error_page 404 = @fallback;
}
location @fallback {
  proxy_pass http://backend;
}
Copy the code

Configuration units in Nginx

Unit of time

  • Ms: milliseconds
  • S: seconds
  • M: Minutes.
  • H: Hours
  • D: Days
  • W: Weeks.
  • M: Months, 30 days
  • Y: Years, 365 days
expires 3m;
Copy the code

Spatial unit

Default: bytes

  • K/k: kilobytes
  • M/m: megabytes
  • G/g: gigabytes
client_max_body_size 10m;
Copy the code

Recommend a document

  • Nginx Location matching rule

Front-End-Basics

Front-end-basics is a technical document that starts from a front-end base and then extends to a full stack.

Github address: github.com/qiqihaobenb…

Document address: docs.chenfangxu.com/