Eight of three phases of Linux: Architecture nginx practical application

Keywords: Linux Nginx Apache PHP curl

8, Architecture nginx practical application

(1) Introduction of web service software

There are three kinds of software commonly used to provide static Web services:

1	Apache:   
This is the mainstream of small and medium-sized Web services, the big brother of web servers.
2	Nginx:    
The mainstream of Web services for large-scale websites, once the newborn calf in web servers, has grown up.
Tengine, a branch of Nginx (http://tengine.taobao.org/), is also growing rapidly.
3	Lighttpd: 
This is an excellent Web software with low temperature and fire. The community is not active and the static parsing efficiency is very high.
Before Nginx became popular, it was the first choice for large concurrent static business. Many websites in China, such as Baidu tieba and Douban, struggled with Lighttpd.

Software commonly used to provide dynamic services

1	PHP(FastCGI): 
Large, medium and small web sites will use, dynamic web page language PHP program parsing container.
It can work with Apache to parse dynamic programs. However, PHP here is not FastCGI daemons, but mod_php5.so (module).
It can also cooperate with Nginx to parse dynamic programs. At this time, PHP often uses FastCGI daemons to provide services.
2	Tomcat: 
The mainstream of dynamic Web services for small and medium-sized enterprises and the mainstream of Internet Java containers (such as jsp and do).
3	Resin: 
The mainstream of large-scale dynamic Web services and Internet Java containers (such as jsp and do).

(2) Introduction to nginx software services

If you have heard or used Apache Software, you will soon be familiar with Nginx software, which is similar to Apache Software,
Nginx ("engine x") is an open-source, high-performance and concurrent WWW server and proxy service software.
It was developed by lgor Sysoev, a Russian, and was originally applied to www.rambler.ru, a large Russian website.
Later, the author open source the source code in the form of BSD like license for global use.
Nginx can run on UNIX, Linux, BSD, Mac OS X, Solaris, Microsoft Windows and other operating systems

(3) Features of nginx software

 Support high concurrency: support tens of thousands of concurrent connections (especially in the static small file business environment)
 Less resource consumption: under 30000 concurrent connections, less than 200MB of memory is consumed to open 10 Nginx threads
 Support asynchronous network I/O event model epoll (Linux 2.6) + apache (select)

(4) Function introduction of nginx software

1) As Web services software (handles user access static requests)
2) Reverse proxy or load balancing service
 3) Front end business data caching service

(5) Features of nginx software model

Comparison between apache and nginx software:
apache uses select model
 nginx uses epoll model
 Example: dormitory administrator
 The administrator of select model version will query the room by room
 The administrator of epoll model version will directly find the person to be found after searching
 Example: kindergarten aunt
 Aunt of select model will ask a child to confirm which child needs to go to the toilet
 The aunt of epoll model will tell the children who want to go to the toilet to stand at the response position consciously

(6) nginx software compilation and installation

First mileage: software dependency package installation

pcre-devel:    perl Language regular expression compatibility package
openssl-devel: Enable system support https Access by
yum install -y pcre-devel openssl-devel

Second milestone: create a virtual user to manage the nginx process

useradd www -s /sbin/nologin/ -M

Third mileage: Download and decompress nginx software

cd /server/tools
wget http://nginx.org/download/nginx-1.12.2.tar.gz
tar xf nginx-1.12.2.tar.gz 

The fourth mileage: software compilation and installation

① . compile configuration
./configure --prefix=/application/nginx-12.2 --user=www --group=www --with-http_ssl_module --with-http_stub_status_module
 --prefix=PATH specifies the directory where the software is installed
 --user=USER specifies software worker process to manage users, and uses www virtual user to manage worker process
--group=USER 
--With HTTP? SSL? Module enables nginx programs to support HTTP SF access
 --With HTTP? Stub? Status? Module is used to monitor users' access to nginx services	
② . compile process make
 ③ . make install

The fifth mileage: create a link directory for nginx program software

ln -s /application/nginx-12.2 /application/nginx	

The sixth mileage: start nginx program service

/application/nginx/sbin/nginx

(7) Directory structure of nginx software program

Conf -- directory for saving all configuration files of nginx program
 Nginx.conf nginx program main configuration file
 To simplify the content of nginx.conf configuration file:
grep -Ev "#|^$" nginx.conf.default >nginx.conf

The nginx configuration file consists of:
① . main nginx main block
 ② . event nginx event block
 ③ . HTTP nginx HTTP function block
 ④ . server nginx website host block
 ⑤ . location nginx match or locate block

html --- nginx program site directory
 Logs --- directory of nginx program log file
 SBIN -- directory of nginx program command
 nginx command parameter description:
-V -- View nginx software compilation configuration parameters
 -t -- check whether the syntax format of nginx configuration file is correct
 -s -- used to manage the running state of nginx service
 Stop stop nginx service
 reload smoothly restarts nginx server
 Restart nginx service
 nginx -s stop stop first 
nginx restart

(8) Writing nginx service configuration

Three syntax formats:
①. Braces should appear in pairs
②. Each line of instructions is followed by a semicolon
③. Each instruction is placed in a specified block

//Write a website page
worker_processes  1;
events {#Event block
worker_connections  1024;
}
http {#http function block
include       mime.types;
default_type  application/octet-stream;
sendfile        on;
keepalive_timeout  65;
server {#Website host block
listen       80;
server_name  www.etiantian.org;
location / {#Match location block
root   html/www;#Site directory for the program
index  index.html index.htm;
}
}
}

//Write multiple web pages = = write multiple virtual hosts (equal to one web site)

The first mileage preparation profile:

  server {
    listen       80;
    server_name  www.etiantian.org;
    location / {
        root   html/www;
        index  index.html index.htm;
    }
    }
    server {
        listen       80;
        server_name  bbs.etiantian.org;
        location / {
            root   html/bbs;
            index  index.html index.htm;
        }
    }
    server {
        listen       80;
        server_name  blog.etiantian.org;
        location / {
            root   html/blog;
            index  index.html index.htm;
        }
    }

Create site directory for the second mileage:

mkdir -p /application/nginx/html/{www,bbs,blog}

The third mileage creates the homepage file under the site directory:

for name in www bbs blog;do echo "10.0.0.7 $name.etiantian.org" >/application/nginx/html/$name/index.html;done
for name in www bbs blog;do cat /application/nginx/html/$name/index.html;done
10.0.0.7 www.etiantian.org
10.0.0.7 bbs.etiantian.org
10.0.0.7 blog.etiantian.org

The fourth mileage: access test

Browser access test:
Note: the windows host hosts file needs to be written for parsing
 Command line access test:
Using curl command to access test in linux system
 Note: you need to write the linux host hosts file for parsing

How to write the virtual host configuration file:
① . domain name based virtual host configuration method (most commonly used)
② . port based virtual host configuration method
 Note: when the domain name of the website you visit does not exist in the virtual host configuration, the configuration page of the first virtual host will respond to the user by default
 ③ . configuration method of virtual host based on IP address
 Note: as long as the modification of IP address is involved in nginx service, it is necessary to restart nginx service instead of smooth restart

(9) Nginx service log information

Error log access log

1. Error log

  Syntax:	error_log file [level];
   Default:	
   error_log logs/error.log error;
   Context:	main, http, mail, stream, server, location
   #error_log  logs/error.log;
   #error_log  logs/error.log  notice;
   #error_log  logs/error.log  info;
   
   vim nginx.conf
   error_log  /tmp/error.log error;
   
   Supplementary notes:
   ===========================================================================================
   It doesn't matter if the error log is not specified by default, because nginx has few error logs.
   But sometimes when there is a problem, it is necessary to record the error log to facilitate our troubleshooting.
   The error log level is divided into debug, info, notice, warn, error, crit, which is crit by default 
   This level is defined after the log name in the following format:
   error_log  /your/path/error.log crit;  
   
   crit records the least logs, and debug records the most logs.
   If nginx encounters some problems, such as 502, it appears frequently, but the default error log does not show meaningful information,
   Then you can adjust the level of the error log. When you set the error level, the content of the error log will be more abundant
   ===========================================================================================

2. Access log (focus)

   Log ﹣ format main '$remote ﹣ addr - $remote ﹣ user [$time ﹣ local] "$request"' -- define the content format of log information to be recorded
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
   Access > log logs / access.log main; --- call to define format information and generate access log
   $remote_addr 10.0.0.1 -- access the source address information of the client
   Remote user: access the client authentication user information???
   [$time [local] - display access time
   $request get / HTTP / 1.1 - request line information
   $status 304 - status code information (304 status code uses cache to display page information)
   $body_bytes_sent -- data size information of the server responding to the client
   $http ﹣ -- record the domain name information linked to the website???
   $http ﹣ user ﹣ agent --- user access website client software identification information
                                             When users use client browser to test access, the default browser of win10 will have an exception
   $http_x_forwarded_for                 --- ???   Reverse proxy
   Official link: http://nginx.org/en/docs/http/ngx-http-log-module.html-access-log
  1. Log to be cut

    01. utilize shell Script to realize log cutting
    [root@web01 scripts]# vim cut_log.sh
    #!/bin/bash
    
    data_info=$(date +%F-%H:%M)
    
    mv /application/nginx/logs/www_access.log /application/nginx/logs/access.log.$data_info
    /application/nginx/sbin/nginx -s reload
    
    # cut nginx log cron
    * */6 * * * /bin/sh /server/scripts/cut_log.sh &>/dev/null
    

(10) Nginx service location block description

location block can be used to locate or match website resource information
Enterprise demand solution
Build a nginx web server. Configure the internal card address and external card address
The domain name of the web service website is www.etiitanian.org, and the site directory is html/www
Intranet users are required to visit the website http://www.etiitanian.org/av resource information
Require internet users not to visit the website http://www.etiitanian.org/av resource information

① How to use nginx for access control

   deny allow
   ngx_http_access_module    --- Implement access control module
   //Official link: nginx.org/en/docs/http/ngx-http-access-module.html
   location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
    }

② . how to locate site directory resource information

   location block to locate the resource information under the site directory
   Syntax: 	location [ = | ~ | ~* | ^~ ] uri { ... }
   location @name { ... }
   Default: 	—
   Context: 	server, location
   Official link: http://nginx.org/en/docs/http/ngx-http-core-module.html-location
   

First mileage: writing nginx configuration file

   server {
        listen       80;
        server_name  www.etiantian.org;
        root   html/www;
        index  index.html index.htm;
        location /AV {
           allow   172.16.1.0/24;
           deny    10.0.0.0/24;
        }
    } 

Second milestone: create test access resources

mkdir AV
echo "AV info" >AV/oldboy.html
cat AV/oldboy.html 

The third mileage: restart nginx service

/application/nginx/sbin/nginx -t
/application/nginx/sbin/nginx -s reload

location [ = | ~ | ~* | ^~ ] uri { ... }
=     --- Match site exactly uri resource information 
~     --- Match case web site uri resource information 
~*    --- Match site case insensitive uri resource information 
^~    --- Match websites first uri resource information 
/AV/  --- Specify matching site resource catalog information
/     --- Default matching site resource information
!     --- Reverse matching content

location = / {
[ configuration A ]       --- Highest priority ①
}

location / {                  --- When all matches are not satisfied, the match defaults to location ④
[ configuration B ]
}

location /documents/ {        --- Match by resource directory         ③
[ configuration C ]
}

location ^~ /images/ {        --- Priority matching ②
[ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {  --- Match site resources not case sensitive  ③
[ configuration E ]
}

(11) Function description of Nginx service rewrite Module

01. Realize domain name address information jump
02. For pseudo static
www.etiantian.org/oldboy?edu.html   ---dynamic resource
www.etiantian.org/oldboy-edu.html   ---Pseudostatic

//Realize the function similar to Baidu rewriting domain name?
baidu.com  ===>  www.baidu.com
etiantian.org  ===> www.etiantian.org

rewrite 
Syntax: 	rewrite regex replacement [flag];
Default: 	—
Context: 	server, location, if

last
stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI; 
break
stops processing the current set of ngx_http_rewrite_module directives as with the break directive; 
redirect
returns a temporary redirect with the 302 code; used if a replacement string does not start with "http://", "https://", or "$scheme"; 
permanent
returns a permanent redirect with the 301 code. 



rewrite Instruction practice operation 1: (error)
[root@web01 extra]# cat bbs.conf 
server {
listen       80;
server_name  www.etiantian.org bbs.org;
rewrite ^/(.*) http://www.etiantian.org/$1 permanent;
root   html/bbs;
index  index.html index.htm;
}

[root@web01 extra]# curl -L etiantian.org 
curl: (47) Maximum (50) redirects followed
[root@web01 extra]# Curl - LV etiitanian.org -- show infinite loop process
//Note: the above configuration is in infinite loop state

rewrite Instruction practice operation 2: (correct)
cat bbs.conf 
server {
listen 80;
server_name etiantian.org;
rewrite ^/(.*) http://bbs.etiantian.org/$1 permanent;
}
server {
listen       80;
server_name  bbs.etiantian.org ;
root   html/bbs;
index  index.html index.htm;
}

rewrite Instruction practice operation three: (correct)
[root@web01 extra]# cat bbs.conf 
server {
listen       80;
server_name  bbs.etiantian.org ;
if ($host ~* "^etiantian.org$") {
rewrite ^/(.*) http://bbs.etiantian.org/$1 permanent;
}
root   html/bbs;
index  index.html index.htm;
}

Posted by cdinca on Sat, 02 May 2020 14:52:31 -0700