Nginx installation

1. Introduction to Nginx

Nginx is a high-performance WEB server. In addition to Apache, Tomcat, Jetty and IIS, they are all WEB servers, or World Wide WEB (WWW) servers, and have the basic functions of WEB servers accordingly. What advantages does Nginx have over other WEB services?

(1) Tomcat and Jetty are Java language oriented, inherently heavyweight WEB servers, and their performance is not comparable with Nginx.

(2) IIS runs only on Windows operating systems. Windows is less stable as a server than uniX-like operating systems in terms of stability and other performance, so IIS is not superior in situations where a high-performance Web server is required.

(3) Apache has a long development period, and is currently the world’s largest Web server without dispute. It has many advantages, such as stability, open source, cross-platform, etc., but it appeared for too long. When it arose, the industrial scale of Internet was far less than that of today. So it is designed to be a heavyweight Web server that does not support high concurrency. On the Apache server, if tens of thousands of concurrent HTTP requests are accessed at the same time, the server will consume a lot of memory. Switching between hundreds of Apache processes by the operating system kernel will consume a lot of CPU resources and reduce the average response speed of HTTP requests. All of this made It impossible for Apache to become a high-performance Web server, which led to the emergence of Lighttpd and Nginx. The chart below shows the strong growth from 2007 to 2018.

2. Compile and install

Installation Environment

(1) Liunx kernel 2.6 and above: Epoll was only supported after 2.6. Before this, the IO model using SELECT or poll multiplexing could not solve the problem of high concurrency pressure. To view the information, run the uname -a command.

# Check the Linux kernel uname -aCopy the code

GCC (GNU Compiler Collection) is used to compile C programs. Nginx does not provide binary executables directly, only the source code can be downloaded and compiled.

The Perl Compatible Regular Expressions library (PCRE) is a Perl Compatible Regular Expressions library developed by Philip Hazel. It is currently used by many software programs.

The zlib library is used to compress HTTP packets in gzip format, if we configure gzip on in nginx.conf and specify gzip for some content-type HTTP responses to reduce network traffic.

If we have a server that not only needs to support HTTP, but also needs to transport HTTP over the more secure SSL protocol, then we need to have OpenSSL. Also, if we want to use hash functions such as MD5 and SHA1, we need to install it.

The above libraries are all necessary for the basic functionality of Nginx. For simplicity, we can install them using the yum command.

#yum install nginx environmentYum -y install make zlib zlib-devel GCC c++ libtool openssl openssl-devel pcre pcre-devel http://nginx.org/en/download.html. 天安门事件# Download the latest stable version of NginxWget HTTP: / / http://nginx.org/download/nginx-1.15.9.tar.gz# decompressionTar -zxvf nginx-1.15.9.tar.gzUse the default installation/configure make && make install The nginx run file will be installed in /usr/local/ nginx. Build based on arguments./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-debug# default boot mode:
./sbin/nginx 
# specify the profile to start
./sbing/nginx -c /tmp/nginx.conf 
# specify the nginx program directory to start
./sbin/nginx -p /usr/local/nginx/

# Quick stop
./sbin/nginx -s stop
# Elegance stop
./sbin/nginx -s quit

Hot load configuration files
./sbin/nginx -s reload
# Reopen the log file
./sbin/nginx -s reopen
Copy the code

Nginx architecture description

Nginx architecture diagram:

Architecture description:

(1) When nginx is started, two types of processes are generated, one is the Master process, one (currently only one in the Windows version) and multiple Worker processes. The main process does not handle network requests, but schedules worker processes, which are the three shown here: loading configuration, starting worker processes, and non-stop upgrades. So, after nginx is started, if you look at the operating system process list, you can see that there are at least two Nginx processes.

(2) The server actually handles network requests and responds to worker processes. On unix-like systems, Nginx can be configured with multiple workers, and each worker process can simultaneously handle thousands of network requests.

(3) Modular design. Nginx worker includes core and functional modules. The core module is responsible for maintaining a run-loop and performing module functions at different stages of network request processing, such as network read and write, storage read and write, content transfer, outgoing filtering, and sending requests to upstream servers. The modular design of its code also makes it possible for us to select and modify the functional modules appropriately according to needs and compile them into servers with specific functions.

(4) Event-driven, asynchronous, and non-blocking are the key factors for nGINx to achieve high concurrency and high performance. It also benefits from the adoption of event notification and I/O performance enhancement features in Linux, Solaris, and BSD-like operating system kernels, such as KQueue, epoll, and Event ports.

Nginx core module:

Nginx configuration and use

(1) Configure the syntax format of the file

(2) Configure the first static WEB service

(3) Configuration cases

A. Static and static separation B. Anti-theft link C. Multi-domain site D. download speed limit e. IP blacklist F. User-agent-based shuntCopy the code

(4) Log configuration

Let’s start with a simple nginx configuration

worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } location /nginx_status { stub_status on; access_log off; }}}Copy the code

Events, HTTP, server, location and upstream in the above configuration belong to the configuration item block. Worker_processes, worker_connections, include, and LISTEN are attributes in the configuration item block. / nginx_STATUS specifies a parameter parameter that belongs to the configuration block. The Server block is nested in the HTTP block and can directly inherit and access the parameters in the HTTP block.

The configuration block A name begins with a large number wrapped around its corresponding property
attribute Based on the whitespace split attribute name and attribute value, the attribute value may have multiple entries split by Spaces, such as access_log logs/host.access.log main
parameter It is configured between the block name and braces, and is separated by Spaces if there are more than one value

Notice If the value of a configuration item contains a syntax symbol, such as a space character, use single or double quotation marks to enclose the value. Otherwise, Nginx will report a syntax error. Such as:

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';
Copy the code

2. Configure the first static WEB service

Basic site demo:

  • Create the site directory mkdir -p /usr/www/luban
  • Writing a static file
  • Configure nginx. Conf
  • Configure the server
  • Configure the location

Basic configuration description:

(1) Listen port syntax: listen address: default: listen 80; Configuration block: Server

Server_name name[…] ; Default: server_name “”; Configuration block: Server server_name can be followed by multiple host names, such as server_name www.testweb.com and download.testweb.com. . Supports wildcard and re characters

(3) the location of the grammar: the location [= | | | ~ ~ * ^ ~ | @] / uri / {… } Configuration block: server

  • / Based on uri directory matching
  • = indicates that the URI is taken as a string to match exactly the URI in the parameter.
  • ~ indicates that the re is case-sensitive when matching urIs.
  • ~ * indicates that case is ignored when matching urIs.
  • ^ ~ indicates that only the first half of the re matches the URI parameter.

Static and static separation demonstration:

  • Creating a Static site
  • configurationlocation /static
  • configuration~* \.(gif|png|css|js)$Dynamic and static separation based on directory
   server {
        listen 80;
        server_name *.luban.com;
        root /usr/www/luban;
        location / {
                index luban.html;
        }
        location /static {
         alias/usr/www/static; }}Copy the code

Based on regular static and static separation

location ~* \.(gif|jpg|png|css|js)$ {
      root /usr/www/static;
}
Copy the code

Anti-theft chain configuration demonstration: add to the specified location can be achieved

valid_referers none blocked *.luban.com;
 if ($invalid_referer) {
       return 403;
}
Copy the code

Download speed limit:

location /download {
    limit_rate 1m;
    limit_rate_after 30m;
}
Copy the code

Creating an IP address blacklist Create a blacklist file

echo 'deny 192.168.0.132; ' >> balck.ip
# add blacklist file to HTTP configuration block
include       black.ip;
Copy the code

3. Log configuration:

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

Logs are generated based on domain names

access_log logs/$host.access.log main;
Copy the code

Error log Settings

Syntax: error_log /path/file level;

Default: error_log logs/error.log error;

Level indicates the log output level. The value can be DEBUG, INFO, NOTICE, WARN, Error, crit, Alert, or emerg. Debug logs are generated for specific clients

Grammar: debug_connection [IP | CIDR]

Events {debug_connection 192.168.0.147; Debug_connection 10.224.57.0/200; }Copy the code