Getting started with nginx

Posted by RDFrame on Tue, 25 Jan 2022 06:52:12 +0100

The configuration system of Nginx consists of a main configuration file and some other auxiliary configuration files. These configuration files are plain text files, all located in the conf directory under the Nginx installation directory

A line starting with # or a line preceded by several spaces or tabs and followed by # in the configuration file is considered a comment;

The configuration file can contain several configuration items. Each configuration item is composed of "configuration instruction" and "instruction parameters", and is represented by; At the end, the instruction parameter is the configuration value corresponding to the configuration instruction. for instance:

# This line is the comment, and the error in the next line_ Page is "configuration instruction", followed by the corresponding "instruction parameters"
error_page   500 502 503 504  /50x.html;

Configuration instruction

There are two types of configuration instructions:

  • Simple configuration instruction: the parameters of the instruction are all composed of simple strings and do not contain composite configuration blocks. The above "error_page" is a simple configuration item;

  • Complex configuration instruction: it includes composite configuration block. Composite configuration block is a pile of instructions enclosed by {}, which may include one or more simple configuration instructions and complex configuration instructions, such as:

events {
    worker_connections   1024;
}

Instruction parameters

The parameters of the instruction are separated from the instruction by one or more spaces or TAB characters, which are composed of one or more TOKEN strings, and the TOKEN strings are separated by spaces or TAB keys;

Instruction context

http, location, server and mail in the complex configuration instruction will generate instruction context. The instruction context has a nested relationship, such as:

# main context
user  nginx;
worker_processes  1;
error_log  logs/error.log  info;

events {
    worker_connections  1024;
}

http {
    server {
        listen          80;
        server_name     www.example.com;
        location / {
            index index.html;
        }
    }
}

mail {
    auth_http  127.0.0.1:80/auth.php;
    pop3_capabilities  "TOP"  "USER";
    imap_capabilities  "IMAP4rev1"  "UIDPLUS";

    server {
        listen     110;
        protocol   pop3;
        proxy      on;
    }
}

The main context is mainly used to configure logic independent of specific business (http or email), such as the following in the example:

  • error_log configuration error log path;

  • worker_processes = number of worker processes

  • User specifies the user and user group that can run the Nginx service;

  • events configures the network connection between the Nginx server and the user, such as the "worker" described above_ Connections is used to configure the maximum number of connections that the worker process can support at the same time;

The main context also contains http instructions. http is the most important part of the configuration of Nginx server. Most functions such as proxy and cache and the configuration of third-party modules can be put into this module; Mail can be used to define the configuration related to the e-mail proxy server;

Common instructions

include

Importing configurations from other files can be used to split complex Nginx configurations;

# main context
user  nginx;
worker_processes  1;
error_log  logs/error.log  info;

events {
    worker_connections  1024;
}

http {
    server {
        listen          80;
        server_name     www.example.com;
        location / {
            index index.html;
        }
    }
    include /etc/nginx/conf.d/*.conf;
}

server

The server block is used to configure the "virtual server". Each server block is equivalent to a "virtual server". The "virtual server" is a concept corresponding to the entity server. An entity server is divided into multiple servers, which can make full use of the hardware resources of the server, And it is not necessary to provide a separate Nginx server for each website to run;

server {
    listen 80;
    server_name a.com;

    location / {
        proxy_pass https://www.baidu.com;
    }
}
server {
    listen 80;
    server_name b.com;

    location / {
        proxy_pass https://www.google.com;
    }
}

The two most important commands in the server are listen and server_name, these two instructions jointly determine which "virtual server" a request will hit;

listen

ip and port used to configure "virtual server" listening can only be configured in the server block. The specific syntax is as follows:

# Only listen for requests from the IP 127.0.0.1 requesting port 8000
listen 127.0.0.1:8000;
# Only listen for requests from port 80 of the IP 127.0.0.1 (no port specified, default 80)
listen 127.0.0.1;
# Listen for requests from all IP ports
listen 8000;
# Listen for requests from port 80, and if there are no other servers_ If name can match, it will match the server by default
listen 80 default_server;

server_name

The web address used to configure the "virtual server" can only be configured in the server block. The specific syntax is as follows:

server_name    myserver.com    www.myserver.com;
# You can also use wildcards*
server_name    myserver.*    *.myserver.com;
# You can also use regular
server_name    ~^(?<www>.+).example.org$;

If there are wildcards and regular characters, there are multiple servers_ The name may be matched at the same time. If there are multiple matches, the "virtual server" to which the request is sent will be determined according to the following priority:

  1. Accurately matched server_name;

  2. The server that the wildcard matches at the beginning_ name;

  3. The server that the wildcard matches at the end_ name;

  4. Regular expression matching server_name;

Use listen and server in server_name to distinguish "virtual server", and the location instruction allows the server to process requests flexibly;

Syntax structure of location:

location [ = | ~ | ~* | ^~ ] uri {
    ...
}

location has five matching methods:

emptyAfter location, there is no parameter directly followed by the {standard URI, indicating prefix matching and matching from the beginning with the URI in the request;
=Before using the standard URI , the request string is required to match it exactly. If it is successful, it will be processed immediately, and nginx will stop searching for other matches.
^~It is used before the standard URI and requires that it will be processed immediately once it is matched. It is no longer used to match other regular URIs. It is generally used to match directories
~Used before regular URI , indicates that the URI contains regular expressions, which is case sensitive
~*Used before the regular URI , indicates that the URI contains a regular expression and is not case sensitive

In Nginx, the matching will not be performed directly according to the order of location, but according to the following rules:

  1. First, accurate matching =, if the accurate matching is successful, other types of matching will be stopped immediately;
  2. Prefix matching is performed when no exact matching is successful. First find the prefix matching with ^ ~. If the prefix matching with ^ ~ is successful, other types of matching will be stopped immediately. If the ordinary prefix matching (without parameter ^ ~) is successful, it will be temporarily stored and continue to find regular matching;
  3. =On the premise that both and ^ ~ are not matched successfully, find the regular matching ~ and ~ *. When there are multiple regular matches at the same time, they will be matched first according to the order in which they appear in the configuration file. If they hit, other types of matching will be stopped immediately;
  4. When all regular matches are unsuccessful, return the common prefix matching (without parameter ^ ~) temporarily stored in step 2;
  5. When all matches fail to hit, enter / by default;

rewrite and proxy_pass

Rewrite can appear in the server, location and if blocks to rewrite the request address. The specific syntax is as follows:

rewrite regex replacement [last|break|redirect|permanent];

proxy_pass can only appear in the location and if blocks to forward the request to the corresponding service. The specific syntax is as follows:

proxy_pass uri;

for instance:

server {
    rewrite /a.html /b.html break;
    return 200 'ok';
    
    location /a.html {
        return 200 'a.html';
    }
    
    location /b.html {
        return 200 'b.html';
    }
    
    location /c.html {
        proxy_pass http://www.google.com;
    }
}

Usage scenario

Domain name - > domain name

After the request of a domain name is intercepted locally, it is forwarded to nginx, and nginx forwards the request to other domain names;

server {
    listen 80;
    server_name www.baidu.com;
    location / {
        proxy_pass http://www.google.com;
    }
}

Domain name - > local ip

After intercepting the request of a domain name, go to nginx, and nginx will call the corresponding request to other local ip addresses;

server {
    listen 80;
    server_name www.baidu.com;
    location / {
        proxy_pass http://127.0.0.1:8001;
    }
}

Path - > domain name

Forward the request to different domain names according to different paths;

server {
    listen 80;
    server_name www.baidu.com;
    
    location ^~ /to_google {
        proxy_http_version 1.1;
        rewrite .* /;
        proxy_pass http://google.com/;
    }
}

Interface Cross Domain

Solve the cross domain problem when the front-end local development environment calls the online interface;

server {
    listen 80;
    
    location ^~ /api {
        proxy_pass http://example.com;
        
        add_header Access-Control-Allow-Methods *;
        add_header Access-Control-Max-Age 3600;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Origin $http_origin;

        if ($request_method = OPTIONS){
            return 200;
        }
    }
}

Topics: Linux Operation & Maintenance Nginx