Overview and configuration of Nginx

1, Nginx overview

1. Characteristics of Nginx

A high-performance, lightweight web service

• high stability

• low and high system resource consumption

• ability to handle HTTP concurrent connections

A single physical server can support 30000 ~ 50000 concurrent requests

2. Nginx compilation and installation

• install support software

• create and run users, groups

• compile and install Nginx

3. Nginx operation control

• check the configuration file

• start, reload configuration, stop Nginx

4. Differences between Nginx and Apache

4.1 advantages of nginx over apache:

Lightweight, it also serves as a web service, occupying less memory and resources than apache

Anti concurrency. Nginx handles requests asynchronously and non blocking, while apache is blocking. Under high concurrency, nginx can maintain low resources, low consumption and high performance

Highly modular design, writing modules is relatively simple

4.2 advantages of Apache over nginx:

Rewrite is more powerful than nginx's rewrite (the main function of rewrite is to jump the URL of the uniform resource locator)

There are many modules. You can find everything you think of

Fewer bugs, and nginx has relatively more bugs


Summary: in general, web services that require performance use nginx. If you don't need performance and just want stability, choose apache

2, Steps for compiling and installing Nginx service

1. Close the firewall and transfer the software package required to install nginx to the / opt directory

systemctl stop firewalld
systemctl disable firewalld
setenforce 0
# Transfer the compressed package to the / opt directory

2. Install dependent packages

The configuration and operation of nginx need the support of software packages such as pcre and zlib. Therefore, these installed development packages need to be installed in order to provide corresponding libraries and header files

yum install -y pcre-devel zlib-devel gcc gcc-c++ make

3. Create and run users and groups (Nginx service program runs as nobody by default. It is recommended to create a special user account for it to more accurately control its access rights)

useradd -M -s /sbin/nologin nginx

4. Compile and install nginx

cd /opt
tar zxvf nginx-1.12.0.tar.gz
./configure \
> --prefix=/usr/local/nginx \            #Specify the installation path of nginx
> --user=nginx \                     #Specify user name
> --group=nginx \                        #Specify group name
> --with-http_stub_status_module     #Enable http_stub_status_module module is calculated by variable holding state line
 make && make install
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/          ##Let the system recognize the operation commands of nginx

5. Check, start, restart and stop nginx service

nginx -t  #Check whether the configuration file is configured correctly
#stop it
cat /usr/local/nginx/logs/nginx.pid                 #First check the PID number of nginx
kill -3 <PID number>                                    #Direct kill
kill -s QUIT <PID number>                               #Elegant kill ()
killall -3 nginx
killall -s QUIT nginx
#heavy load
kill -1 <PID number>
kill -s HUP <PID number>
killall -1 nginx
killall -s HUP nginx
#Log split, reopen log file
kill -USR1 <PID number>
#Smooth upgrade
kill -USR2 <PID number>
New version upgrade∶
tar -zxvf nginx-1.xx.xX. tar.gz
cd nginx-1.xx. xx
./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module \
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx_old
cp objs/nginx /usr/local/nginx/sbin/nginx
make upgrade
#Or kill nginx first and then / usr/local/nginx/sbin/nginx

6. Add nginx system service

Method 1: use script

vim /etc/init.d/nginx           #Create a script file as follows:
#chkconfig: - 99 20
#description:Nginx Server Control Script
case "$1" in
   kill -s QUIT $(cat $PID)
   $0 stop
   $0 start
   kill -s HUP $(cat $PID)
echo "Usage:$0 {start|stop|restart|reload}"
exit 1
exit 0
chmod +x /etc/init.d/nginx
chkconfig --add nginx
systemctl daemon-reload          #When the ngin service on the disk changes, run 'systemctl daemon reload' to reload the unit.
systemctl start nginx
systemctl stop nginx

Method 2:

vim /lib/systemd/system/nginx.service
ExecrReload=/bin/kill -s HUP SMAINPID
ExecrStop=/bin/kill-s QUIT $MAINPID
chmod 754 /lib/systemd/ system/nginx.service
systemctl start nginx.service
systemctl enable nginx.service

[Unit]: Description of the service Description: Description of the service after: dependency. After the dependent service is started, start the customized service

[Service] setting of Service operation parameters
Type=forking is the form of background running. When using this startup type, PIDFile = should be specified at the same time, so that systemd can track the main process of the service.
ExecStart is the specific running command of the service, ExecReload is the restart command, and ExecStop is the stop command
PrivateTmp=True indicates that an independent temporary space is allocated to the service. Note: absolute paths are required for start, restart and stop commands

[Install] the relevant settings of service installation can be set to multi-user

3, Instance operation: compile and install Nginx service

1. Close the firewall and transfer the software package required to install nginx to the / opt directory

2. Install dependent packages


3. Create and run users and groups


4. Compile and install Nginx

4.1 unzip the Nginx package


4.2 installation of relevant modules


4.3 compilation and installation


4.4 link Nginx to / user/local/sbin


5. Check, start, restart and stop Nginx service

5.1 inspection and startup


5.2 stop and restart nginx service

5.2.1 stop nginx service


5.2.2 heavy load service

6. Add nginx system service

6.1 vim/lib/systemd/system/nginx.service file and add configuration content

6.2 grant authority and start service


4, Recognize the main profile of the Nginx service

vim /usr/local/nginx/conf/nginx.conf

1. Global configuration

#user  nobody;                          #Run the user. If it is not specified during compilation, it defaults to nobody
worker_processes  1;                    #The number of working processes can be configured as the number of server cores * 2. If the number of website visits is small, it is generally set to 1
#error_log  logs/error.log;             #Location of the error log file
#pid        logs/nginx.pid;             #Location of PID file

2. I/O event configuration

events {
    use epoll;                          #Using epoll model and system kernel of version 2.6 and above, it is recommended to use epoll model to improve performance
    worker_connections  4096;           #Each process handles 4096 connections

If you want to increase the number of connections per process, you also need to execute the command "ulimit -n 65535" to temporarily modify the maximum number of files that each local process can open at the same time.
On the Linux platform, when dealing with highly concurrent TCP connections, the maximum number of concurrent connections is limited by the system to the number of files that can be opened by a single user process at the same time (this is because the system creates a socket handle for each TCP connection, and each socket handle is also a file handle).
You can use the ulimit -a command to view the limit on the number of files the system allows the current user process to open.

3. HTTP configuration

http {
    include       mime.types;                                                ##File extension and file type mapping table
    default_type  application/octet-stream;                              ##Default file type
                                                                              ##Log format setting
    #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;                                        #Log format setting
    sendfile        on;                                                ##Support file sending (downloading)
    ##This option allows or prohibits the use of the TCP cORK option of socket (cache data before sending packets). This option is only used when sendfile is used
    #tcp_nopush     on;
    ##Connection hold timeout, in seconds
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;                                                              ##Gzip module settings, setting whether to enable gzip compressed output
server {
        listen       80;                                        ##Monitoring port and address
        server_name  www.clj.com;                                       ##The site domain name can have multiple, separated by spaces
        #charset utf-8;                                         #Default character set for web pages
        #access_log  logs/host.access.log  main;       
        location / {                                            ##Root configuration
            root   html;                                        ##Location of website root directory / usr/local/nginx/html
            index  index.html index.htm;                                        ##Default home page file name
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;                              ##Feedback page for internal errors
        location = /50x.html {                                ##Error page configuration
            root   html;

Log format setting:
$remote_addr and $http x forwarded for are used to record the ip address of the client;
$remote user: used to record the client user name;
$time local: used to record access time and time zone$ Request: the url and http protocol used to record the request;
$status: used to record the request status; Success is 200,
$body bytes sent: record the size of the body content of the file sent to the client;
$http referer: used to record which page link to access from;
$http user agent: record the relevant information of the client browser;

Usually, the web server is placed behind the reverse proxy, so you can't get the customer's IP address through sremote_ The IP address obtained by add is the IP address of the reverse proxy server. The reverse proxy server can add x to the http header information of the forwarding request_ forwarded_ For information, which is used to record the IP address of the original client and the server address requested by the original client.

location common configuration instructions, root, alias, proxy_ pass
root: request ww xkq. com/test/1. Jpg, the file / usr / local / nginx / HTML / test / 1 will be returned jpg
Alias (alias configuration): request www.xkq.com com/test/1. Jpg, the file / usr / local / nginx / HTML / 1 will be returned jpg

5, Access status statistics configuration

1. Steps to access status statistics configuration

1.1. First use the command / usr/local/nginx/sbin/nginx -V to check whether the installed Nginx contains HTTP_STUB_STATUS module

1.2. Modify nginx Conf configuration file, specify access location and add stub_status configuration (backup before modification)

cd /usr/local/nginx/conf/
cp nginx.conf nginx.conf.bak
vim nginx.conf
server {
        listen       80;
        server_name  www.clj.com;
        charset utf-8;
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.html index.htm;
        ##Add stub_status configuration
        location /status {              ##The access location is / status
            stub_status on;             ##Turn on the status statistics function
            access_log off;             ##Turn off logging at this location

1.3 restart the service and access the test

systemctl restart nginx

Browser access http; //

Active connections: indicates the current number of active connections;
Server accepted handled requests: indicates the connection information that has been processed. The three numbers in turn indicate the number of connections processed, the number of successful TCP handshakes, and the number of requests processed.
curl http: / / can be combined with awk and if statements for performance monitoring

2. Instance operation: access status statistics configuration

2.1 use the command / usr/local/nginx/sbin/nginx -V to check whether the installed Nginx contains HTTP_STUB STATUS module


2.2 modify nginx Conf configuration file, specify access location and add stub_status configuration


2.3 access test after restarting the service

6, Authorization based access control

1. Operation steps of authorization based access control

1.1 generate user password authentication file

yum install -y httpd-tools
htpasswd -c /usr/local/nginx/passwd.db zhangsan
chown nginx /usr/local/nginx/passwd.db
chmod 400 /usr/local/nginx/passwd.db

1.2 modify the directory corresponding to the main configuration file and add authentication configuration items

vim /usr/local/nginx/conf/nginx.conf
   server {
      location / {
      ##Add authentication configuration##
    auth basic "secret";     #Set password prompt box text message
    auth_basic_user_file /usr/local/nginx/passwd.db;

1.3 restart service and access test

nginx -t
systemctl restart nginx.service

Visit via browser

2. Instance operation: authorization based access control

2.1 generate user password authentication file

2.2 modify the directory corresponding to the main configuration file and add authentication configuration items

2.3 restart service and access test



3. Client based access control

3.1 operation steps based on client access control

The access control rules are as follows:

• deny IP/IP segment: deny client access to an IP or IP segment

• allow IP/IP segment: allow client access to an IP or IP segment

• the rule is executed from top to bottom. If it matches, it will stop and no longer match from bottom to top

vim /usr/local/nginx/conf/nginx.conf
 location / {
            root   html;
            index  index.html index.htm;
            auth_basic "secret";
            auth_basic_user_file /usr/local/nginx/passwd.db;
            # Add control rule
            deny;                 #Access denied client IP
            allow all;                          #Allow all other clients to access
systemctl restart nginx

3.2 instance operation: Based on client access control

3.2.1 add control rules in the main configuration file


3.2.2 restart the service and access the test

Use the denied client for access testing


Use other clients for access testing

Posted by millesm on Tue, 03 May 2022 14:33:21 +0300