What is the Nginx

Common Server

The agent

Forward agent

The client requests a proxy server between the target servers. The request passes through the proxy server, then forwards the request to the target server, retrives the content, and finally responds to the client

The reverse proxy

The client requests the target server, and the proxy server decides which IP to access

The installation

See nginx Installation configuration

The configuration commands are listed as follows:

The command explain
– the prefix Specify the nginx installation directory
– pid – path Pid pointing to nginx
– the lock – path Lock installation files to prevent maliciously tampered or misoperated files
– the error log The error log
– HTTP – log – path HTTP log
– with – http_gzip_static_module Enable the GZIP module to compress the output data stream online in real time
– HTTP client – body – temp – path Set the temporary directory requested by the client
– HTTP proxy – temp – path Set the HTTP proxy temporary directory
– HTTP – fastcgi – temp – path Set up the fastCGI temporary directory
– HTTP – uwsgi – temp – path Set up the UWSGi temporary directory
– HTTP – scgi – temp – path Set up the SCGI temporary directory

Nginx process model

  • Master process: the main process, one
  • Worker process: worker process, one by default, can be configured in nginx.conf
# nginx.conf
worker_processes	2;
Copy the code

Signals (such as./ nginx-s reload) are sent to the main process, which is assigned to the worker process and actually executed by the worker process.

Worker preemption mechanism

When the client requests an accept_mutex lock, the worker contests the accept_mutex lock.

Nginx event processing

The epoll non-blocking event model is used by default.

# nginx.conf events {# epoll use epoll; # worker_connections 1024; }Copy the code

Nginx.conf configuration structure

user

The user who sets the worker process, a Linux user, has access to nginx for directories or files. The default is nobody

user root;
Copy the code

Worker Number of work processes

In general, if you have a few cpus, you can set it to a few, or you can set it to n-1

worker_processes    1;
Copy the code

Nginx log level

The debug | info | notice | warn | error | crit | alert | emerg, error level from left to right is more and more big

error_log  logs/error.log  info;
Copy the code

Nginx process

pid    logs/nginx.pid
Copy the code

Working mode

Events {# epoll use epoll; # worker_connections 1024; }Copy the code

The HTTP commands block

Some instruction configurations for HTTP network transport

http {
}
Copy the code

include

External configuration is introduced to improve readability and avoid large single configuration files

include    mime.types;
Copy the code

Log format

Parameter names Parameter meaning
$remote_addr The client IP
$remote_user User name of the remote client, usually: ‘-‘
$time_local Time and Time Zone
$request The requested URL and method
$status Response status code
$body_bytes_send Number of bytes of response client content
$http_referer Record which link the user jumped from
$http_user_agent The agent used by the user is usually a browser
$http_x_forwarded_for A proxy server is used to record client IP addresses
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;
Copy the code

Main is the format name defined so access_log can use the variable directly

sendfile

Sendfile uses efficient file transfer to improve transmission performance. Tcp_nopush can be used only after it is enabled. In this way, data tables are sent only after they have accumulated a certain size, which improves efficiency.

sendfile    on;
tcp_nopush    on;
Copy the code

Timeout of client and server requests

This ensures that the client does not set up new connections repeatedly to save resources.

keepalive_timeout    65;
Copy the code

gzip

Transmission data compression, enabled to save bandwidth, but response will increase CPU load.

gzip  on;
# Limit minimum compression. Files smaller than 1 byte will not be compressed
gzip_min_length  1;
# Define the compression ratio, the higher the value, the more compression, but the more CPU usage
gzip_comp_level  3;
Define the type of file to be compressed
gzip_types  text/plain application/x-javascript text/css application/xml;
Copy the code

server

Virtual host, can configure multiple

server {
}
Copy the code

location

The default matching

location / {
}
Copy the code

Normal match, the path has something to display

An exact match

location = /abc/xxx.png {
}
Copy the code

= Only XXx. PNG can be accessed. Other paths are not matched

Matching regular expressions

location ~* \.(GIF|png) {
}

location ~ \.(GIF|png) {
}
Copy the code

~* indicates case insensitive, and ~ indicates case sensitive

Matches requests that begin with a character path

location ^~ /abc/def {
}
Copy the code

Only resources within/ABC /def can be requested

Examples of complete configuration files

########### Each instruction must end with a semicolon. # # # # # # # # # # # # # # # # #
#user administrator administrators; Configure the user or group. Default is nobody nobody.
#worker_processes 2; # Number of processes allowed to be generated. Default is 1
#pid /nginx/pid/nginx.pid; # specify the location where nginx run files are stored
error_log log/error.log debug;  Specify log path, level. , this setting can fit into a global, HTTP server block, level as: debug | info | notice | warn | error | crit | alert | emerg
events {
   accept_mutex on;   Set network connection serialization to prevent stampedes. Default is on
   multi_accept on;  Set whether a process accepts multiple network connections at the same time. Default: off
   #use epoll; # event driven model, select | poll | kqueue | epoll | who | / dev/poll | eventport
   worker_connections  1024;    # Maximum number of connections. Default is 512
}
http {
   include       mime.types;   File extension and file type mapping table
   default_type  application/octet-stream; The default file type is text/plain
   #access_log off; Cancel service log
   log_format myFormat '$remote_ADDR - $remote_user [$time_local] $request $status $body_bytes_SENT $http_referer $http_user_agent $http_x_forwarded_for'; # Custom format
   access_log log/access.log myFormat;  #combined is the default value for logging format
   sendfile on;   # allow sendFile transfer, default is off, HTTP block, server block, location block
   sendfile_max_chunk 100k;  The number of transfers per call cannot exceed the set value. The default value is 0, that is, no upper limit is set.
   keepalive_timeout 65;  # connection timeout, default is 75s, can be in HTTP, server, location block.Upstream mysvr {server 127.0.0.1:7878; 3333 backup server 192.168.10.121:;# hot standby
   }
   error_page 404 https://www.baidu.com; # error page
   server {
       keepalive_requests 120; # Maximum number of single connection requests.
       listen       4545;   # monitor portServer_name 127.0.0.1;# monitor address
       location  ~*^.+$ {       # request url filtering, regular matching, ~ is case sensitive, ~* is case insensitive.
          #root path; # the root directory
          #index vv.txt; Set the default page
          proxy_pass  http://mysvr;  Request redirected to mysvr defined server listDeny 127.0.0.1;Rejected IPAllow 172.18.5.54;# Allowed IP}}}Copy the code

Nginx common commands

./nginx -h		# View help

./nginx -s stop		# Stop the violence
./nginx -s quit		# Elegance stop
./nginx -s reopen	# to restart
./nginx -s reload	Reload the configuration file

./nginx -t		Test the correctness of the configuration file
./nginx -v		# check the nginx version number
./nginx -V		# view nginx details

./nginx -c filename	# specify the profile to start
Copy the code

Nginx cross-domain configuration

location / { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; if ($request_method = 'OPTIONS') { return 204; }}Copy the code

Preventing hotlinking

If ($invalid_referer) {return $referer; }Copy the code