Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Implementation of Nginx web Server and detailed explanation of function Module instructions under Linux

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Nginx (engine x) is not only a high-performance HTTP and reverse proxy server, but also a lightweight Web server related to the http protocol:

The form of URL uniform resource locator:

Shceme://username:password@host:port/path;params?query#frag

Http transaction: a request and a response constitute a transaction

Request request format:

HEADERS

Response response format:

HEADERS

Method request method: GET/HEAD/POST,PUT/DELETE,TRACES,OPTIONS

Status code:

1xx: 2xx: success response code 3xx: response code of the redirect class 4xx: client error 5xx: server error Nginx configuration file nginx.conf structure:

What is not contained in curly braces is the main block configuration segment, which is also the global configuration segment.

Event {} event-driven configuration segment http {} configuration segment related to http/https mail {} configuration segment related to mail agent stream {} configuration segment related to load balancing the structure of the configuration segment as the configuration segment of the web server http http {... Configure the global configuration segment server {listen 80; server_name www.example.com root / web/hosts/ alias location {OPERATOR} URL {... If CONDITION {...} each server is a virtual site} nginx configuration main block segment related instructions and meaning

Specify the running identity of the work process:

User nginx group

Indicates the storage path of the pid file

Pid / var/run/nginx.pid

Contains other profile fragments

Include file_name | mask

Indicates the module to be loaded dynamically

Load_module file_name

Error log:

Error_log / var/log/nginx/error.log varn; configuration related to system optimization:

The worker process can open the maximum number of file descriptors:

Worker_rlimit_nofile 20; configuration had better be the same as ulimit-n value, modify the number of file descriptors ulimit-HSn 180000

Number of work processes generated

Worker_processes 3 | auto

Priority of the woker process: default is 0

Worker_priority-9

The worker process of nginx is bound to cpu

Wokrer_cpu_affinity 1000 0100 0010 | what auto; cpu mask represents: 1000: the last 0100 of the quad-core cpu: the penultimate cpu of the quad-core cpu. Configuration for debug use:

Whether to run as a daemon

Daemon on | off

Whether to run as a master/worker model

Master_process on | off

Specify the error log path and level

When error_log file warn; specifies the path and name of the error log, you cannot refer to the configuration segment related to the events configuration:

The maximum number of concurrency that each worker process can respond to

Worker_connetctions 65535; the total number of concurrent responses that a server can carry worker_processes * worker_iconnections

Indicates how to handle concurrent link requests:

Use epoll

Methods for worker processes to accept new requests

| accept_mutex on | if off; is on, the worker process will take turns accepting new requests. If it is off, all worker processes will receive notifications. Idle requests will be accepted for configuration related to site sockets server {listen address:port default_server ssl http2 backlog=123 rcvbuf=512 sndbuf=512. | # default_server: specify as default virtual site # ssl: limit only indirect sites through ssl # http2: specify http protocol version # backlog=number: backup queue length # rcvbuf= receive buffer size # sndbuf= send buffer size server_name SERVER_NAME; # SERVER_NAME supports wildcards # for example, * .abc.com # supports ~ regular expressions that begin with characters # for example ~ ^ www. *\ .abc.com $# matching priority: # 1. Exact match # 2. Match # 3 on the left. Match # 4 on the right. The regular expression matches the root directory of the site indicated by root / PATH/DOCUMENT_ROOT;}

Whether the TCP_NODELAY feature is enabled for connections in keepalived mode

Tcp_nodelay on | off

Whether to enable the sendfile feature:

Sendfile on | off

Whether to enable the TCP_CORK function in sendfile mode:

Tcp_nopush on | configuration segment related to the off; path

Specifies the root directory of the site, which is used to map the file system to url

Root path

Matches the relationship between the system paths mapped by URL

Location [= | ~ | ~ * | ^ ~] url {.} there can be multiple location configuration segments in one location configuration segment nginx maps its resources to different paths according to the matching different url =: exactly match the url for example: location = / {...} ~: do regular expression matching for url, case-sensitive characters ~ *: match rul regular expressions, not case-sensitive; ^ ~: match regular expressions in the left half of rul, case-insensitive, unsigned: match priority for all url with the beginning of this url: =, ^ ~, ~ / *, unsigned

Example:

Server {root / web/hosts/vhsost1 location / wcdma {root / web/hosts/wcdma/ index index.html index index.php}}

Define an alias for the path

Location / p_w_picpaths/ {alias / web/data/p_w_picpaths/;}

Define the default home page resources for the site:

Index file; for example: index index.html index.htm index

Define the wrong return page

Error_page 404 / eror_page # relative path

Accept multiple paths as parameters, and automatically find the next one when a resource cannot be found, otherwise find the default location

Try_files file... Url

Example:

Location / {try_files index.html index.htm @ default;} location @ default {root / web/hosts/error; index index.html;} configuration related to client request

Configure the timeout for keeping the link. 0 indicates the binary persistent connection mode.

Keepalive_timeout 75

The maximum number of resources that can be requested on a single persistent connection

Keepalive_requests 100

Which browser disables the long connection mode

Keepalive_disable none | browser

The timeout for sending a response message to the client, which refers to the interval between two write operations

Send_timeout 20

The buffer size used to accept the body portion of the client request message. If this size is exceeded, it will be stored in the location specified by client_body_temp_path on disk.

Client_body_buffer_size size

Specify the location where the body portion of the request message that accepts the client is stored

Client_body_temp_path / var/tmp/client_body 2 11; 2: the first number 2 represents a 2-digit hexadecimal number as a level 1 directory 1: the second number 1 indicates a 1-bit hexadecimal number as a level 2 directory. Configuration related to client restrictions

Limit the transmission rate of the response to the client. Unit is bytes/ second. 0 means unlimited.

Limit_rate 500

Restrict clients except for the specified method

For example: limit_except GET {allow 110.11.223.0Compact 24; deny all;} optimization of file operations:

Whether to enable the aio mechanism

Aio on | off | threads [= pool]

Whether to enable the directio mechanism, enable the O_DIRECT flag on the LINUX host, when the request is greater than the set value

The process that directly skips the kernel cache reads the hard disk directly, which is used for poor hit ratio or large files.

Directio size | off

Whether to enable open file caching:

Open_file_cache off

Open_file_cache max=200 inactive=60

There are three types of information that nginx can cache:

1. File descriptor. File size, last modified time; 2. Open the structure of the directory 3. Information related to files that are not found or do not have permission to access; if the upper limit of max=200 cache items is reached, the LRU algorithm is used to manage the inactive duration of inactive=time cache items, those that are not accessed within a specified time, or whose hits are less than the number of hits specified in the open_file_cache_min_uses instruction.

Cache validity check frequency, time

Open_file_cache_valid 60

Within the time specified by open_file_cache inactive, those whose cache is accessed less than that number are classified as inactive

Open_file_cache_min_users 1

Whether to cache the information of finding errors

Open_file_cache_errors on | configuration related to off;ngx_http_access_module module: allow ipaddress; deny ipaddress;ngx_http_auth_basic_module module

Implement basic authentication based on access control (user files need to be generated with the help of hdpasswd)

Auth_basic string | off; auth_basic_user_file file_name

Example:

Location / admin/ {alias / web/vhosts/app1/data; auth_basic "Admin Area"; auth_basic_user_file / etc/nginx/.ngxpasswd;} ~] # htpasswd-c-m / etc/nginx/.ngxpasswd tomngx_http_stub_status_module module configuration:

Used to output basic status information of nginx:

Active connections: the number of active connections; accepts: the total number of requests accepted by the client; handled: the total number of requests processed; requests: the total number of requests sent by the client; reading: the total number of links at the beginning of reading the client request message; writing: the number of connections in the process of sending a response to the client Waiting: the number of idle connections waiting for a request from the client

Example:

Stub_status; location / basic_status {stub_status;} ngx_http_log_module Log Module

Log format:

Log_format name string; string can use the built-in variable access_log / var/log/nginx/access.log format buffer=512 gzip=1 flush=time if=condition; access_log off; buffer=512 of the nginx core module to define the size of the buffer flush=time refresh time open_log_file_cache max=100 inactive=60 min_uses=1 valid=60; open_log_file_cache off; cache metadata related to each log file Maximum number of file descriptors cached by max minimum number of times min_uses is accessed in inactive time inactive inactive length; time interval for valid to verify whether the buffer item is the active item; ngx_http_gzip_module compression module

The use of compressed transmission when transmitting data

Gzip on | off

Compression level:

Gzip_com_level 1

Indicate which clients do not compress:

Gzip_disable regex...

Indicates the minimum value for compressed transmission

Gzip_min_length 60k

Indicates the number of buffers for compressed transmission and the size of each

Gzip_buffers 20 100

When nginx acts as a proxy server, what are the conditions under which compression is enabled after receiving the response message sent from the proxy server?

Gzip_proxied off | expired | no-cache | nostore | private | no_last_modified | no_etag | auth | any; off: no-cache,no-store,private is not enabled for the proxy request: compression is enabled when the Cahce_control received from the proxy server is one of the three

Enable compression for some types:

Gzip_types mime-type; is a compression filter, only for this type of compression examples: gzip on; gzip_comp_level 6; gzip_min_length 64; gzip_proxied any; gzip_types text/xml text/css application/javascript;ngx_http_ssl_module security module:

Enable https featur

Ssl on | off

Specify the certificate file in ped format used by the host

Ssl_certificate file

Indicates the private key file corresponding to the host certificate

Ssl_certificate_key file

Indicates the version of the ssl protocol

Ssl_protols [SSLv2] [SSLv3] TLSv1 TLSv1.1 TLSv2

Indicates the openssl built-in cache, which is private to each worker process and the size of the shared cache name

Ssl_session_cache off | none | builtin 500 shared:name:500

Indicates how long the client's link can reuse the cached ssl parameter in ssl session cache

Ssl_session_timeout 60

Example:

Server {listen 443 ssl; server_name www.abc.com; root / web/vhsts/ssl/; ssl on; ssl_certificate / etc/nginx/ssl/nginx.crt; ssl_certificate_key / nginx/ssl/nginx.key; ssl_protocols TLSv1 tlsv1.1 tlsv2 sslv2 sslv3; ssl_session_cache shared:sslcache:20m;} ngx_http_rewrite_module module:

The URL requested by the user is checked based on the pattern described by regex, and the matched url will be replaced with the new url

Rewrite regex replacement flag

What is worth noting about this pattern is that if multiple rewrite rules are configured at the same level, they will be matched one by one from the top to the bottom, and the new url will continue to match again after the matching is completed, with a circular mechanism.

The flag bit of [flag] is used to control this loop mechanism; last: stop other subsequent rewriting mechanisms of the current URL in the current location after the rewriting is completed, and then start a new business rewriting mechanism for the new URL. Break: stop the subsequent rewriting of the current URL in the current location after the rewrite is completed, and directly jump out of the rewriting module redirect: after the rewrite is completed, the temporary redirection is returned directly to the client. The client cannot start a new URL with http:// or https://.

If replacement starts with http:// or htts://, the replaced result will be returned directly to the client as the redirected party

Permanent redirect return returns to the client status code return code text; return code URL; return URL

Whether to enable rewrite log:

Return_log on | off

If (condition) {...} statement, which executes the configuration instructions in the configuration block when a new configuration condition is met:

Condition: comparison operator: = =! = ~: pattern matching, case-sensitive; ~ *: pattern matching, not case-sensitive;! ~: pattern mismatch, case-sensitive;! ~: pattern mismatch, not case-sensitive Existence judgment of files and directories:-e,!-e-f,!-f-d,!-d-x,!-x

User-defined variables:

Set $variable value;ngx_http_referer_module module: jump module configuration

Define the legally available values for the referer header

Valid_referers none | blocked | server_names | string..; none: request message header does not have a referer header; blocked: request message referer header has no value; server_name: parameter, value is used as hostname or hostname pattern; arbitrary_string: direct string, but * wildcard can be used; regular expression: string to which the specified regular expression pattern matches To start with ~, for example: ~. *\ .acb\ .com

Example configuration:

Valid_referers none block server_names * .abc.com abc.com ~\ .abc\ .com; if ($invalid_referer) {return 403;}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report