Nginx basic services

Posted by microbluechip on Tue, 25 Jan 2022 16:55:04 +0100

I Nginx overview

  • A high-performance, lightweight Web service software
    • High stability
    • Low system resource consumption
    • High processing capacity for HTTP concurrent connections
    • A single physical server can support 30000 ~ 50000 concurrent requests

II Compiling and installing Nginx services

1. Close the firewall and transfer the software package required for installing Apache to the / opt directory

systemctl stop firewalld
systemctl disable firewalld
setenforce 0

3. Create and run users and groups

  • The 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
yum -y install pcre-devel zlib-devel gcc gcc-c++ make

4. Compile and install Nginx

cd /opt
tar zxvf nginx-1.12.0.tar.gz -C /opt/

cd /opt/nginx-1.12.0/

./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module

make && make install
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/

#-----Configuration command interpretation
--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 to support status statistics
#-----

make && make install

#Let the system recognize the operating commands of nginx
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/



5. Check, start, restart and stop nginx service

nginx -t					           #Check whether the configuration file is configured correctly
#start-up
nginx									
#stop it
cat /usr/local/nginx/logs/nginx.pid		#First check the PID number of nginx
kill -3 <PID number>
kill -s QUIT <PID number>
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 separator, reopen log file
kill -USR1 <PID number>
#Smooth upgrade
kill -USR2 <PID number>

6. Add Nginx system service

Method 1:

vim /etc/init.d/nginx
#!/bin/bash
#chkconfig: - 99 20
#description:Nginx Service Control Script
COM="/usr/local/nginx/sbin/nginx"
PID="/usr/local/nginx/logs/nginx.pid"
case "$1" in
start)
  $COM
;;

stop)
  kill -s QUIT $(cat $PID)
;;

restart)
  $0 stop
  $0 start
;;

reload)
  kill -s HUP $(cat $PID)
;;

*)
echo "Usage: $0 {start|stop|restart|reload}"
exit 1

esac
exit 0


chmod +x /etc/init.d/nginx
chkconfig --add nginx		#Add as system service
systemctl stop nginx
systemctl start nginx

Method 2:

vim /lib/systemd/system/nginx.service
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecrReload=/bin/kill -s HUP $MAINPID
ExecrStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target

chmod 754 /lib/systemd/system/nginx.service
systemctl start nginx.service
systemctl enable nginx.service

III Know the main configuration file of Nginx service Nginx conf

Edit Master profile

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

1. Global configuration

2-9 that 's ok
#user nobody; 					#Run the user. If it is not specified during compilation, it defaults to nobody
worker_processes 1; 			#Number of working processes, which can be configured as the number of server cores * 2
#error_log logs/error.log; 		#Location of the error log file
#pid logs/nginx.pid; 			#Location of PID file

2. I/O event configuration

#About 12-15 rows
events {
    #Epoll model is used, and the system kernel of version 2.6 and above is recommended to use epoll model to improve performance
    use epoll;
    #Each process handles 4096 connections
    worker_connections 4096;
}
#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 can be opened simultaneously by each local process.
#On the Linux platform, when processing 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 that the system allows the current user process to open

uname -r View kernel version


3.HTTP configuration

#About lines 18-57
http {
	#File extension and file type mapping table
    include       mime.types;

	#Default file type
    default_type  application/octet-stream;

	#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 location
    #access_log  logs/access.log  main;

	#Support file sending (downloading)
    sendfile        on;
    #This option allows or disables TCP using socke_ The option of cork (cache data before sending packets), which is only used when sendfile is used
    #tcp_nopush     on;

	#Connection hold timeout, in seconds
    #keepalive_timeout  0;
    keepalive_timeout  65;

	##Gzip module settings, setting whether to enable gzip compressed output
    #gzip  on;

#Listening configuration for Web Services
server {
	#Listening address and port
	listen 80; 
	#The site domain name can have multiple, separated by spaces
	server_name www.lisi.com;
	#Default character set for web pages
	charset utf-8;

	#Root configuration
	location / {
		#Location of the site root directory / usr/local/nginx/html
		root html;
		#Default home page file name
		index index.html index.htm;
	}

	#Feedback page for internal errors
	error_page 500 502 503 504 /50x.html;
	#Error page configuration
	location = /50x.html {
		root html;
	}
  }
}

4. Verify access to web pages

systemctl restart nginx.service
echo "192.168.133.10 www.abc.com" >> /etc/hosts
#Access with browser
http://www.abc.com/
http://192.168.133.10/



5. Log format setting

$remote_addr And $http_x_forwarded_for Used to record the client's ip Address;
$remote_user: Used to record the client user name;
$time_local:  Used to record access time and time zone;
$request:  Used to record requests url And http agreement;
$status:  Used to record request status; Success is 200,
$body_bytes_sent : Record the size of the main content of the file sent to the client;
$http_referer: Used to record the links accessed from that page;
$http_user_agent: Record the relevant information of the client browser;

usually web The server is placed behind the reverse proxy, so the client's information cannot be obtained IP Address, through $remote_add Got it IP The address is the address of the reverse proxy server iP Address. The reverse proxy server is forwarding the request http Header information can be added x_forwarded_for Information to record the information of the original client IP Address and the server address requested by the original client.

location Common configuration instructions, root,alias,proxy_pass
root(Root path configuration)
request www.lisi.com/test,The file is returned/usr/local/nginx/html/test/index.html
alias(Alias configuration)
request www.lisi.com/test,The file is returned/usr/local/nginx/html/index.html

proxypass (Reverse proxy configuration)
#Forward request to http://127.0.0.1:8080/1.jpg
proxy_pass http://127.0.0.1:8080/;
#Forward request to http://127.0.0.1:8080/test/1.jpg
proxy_pass http://127.0.0.1:8080;

Root (root path configuration)




Alias (alias configuration)




IV Access status statistics configuration

1. First check whether the Nginx service contains HTTP_STUB_STATUS module

/usr/local/nginx/sbin/nginx -V

2. Modify nginx Conf configuration file, specify the access location and add stub_status configuration

cd /usr/local/nginx/conf
cp nginx.conf nginx.conf.bak
vim /usr/local/nginx/conf/nginx.conf
......
http {
......
  server {
    listen 80;
    server_name www.abc.com;
    charset utf-8;
    location / {
      root html;
      index index.html index.php;
    }
    #Add stub_status configuration
    location /status {
      stub_status on;
      access_log off;
    }
  }
}



3. Restart the service and access the test

systemctl restart nginx

Browser access http://192.168.133.10/status
Active connections : Indicates the current number of active connections;
server accepts handled requests : Represents the processed connection information. The three numbers represent the number of processed connections and the number of successful connections in turn TCP Number of handshakes, number of requests processed.


V Authorization based access control

1. Generate user password authentication file

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



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";
          auth_basic_user_file /usr/local/nginx/passwd.db;
		}
	}


3. Restart the service and access the test

nginx -t
systemctl restart nginx

Browser access http://192.168.133.10 or www.abc.com com



6, Client based 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: allows 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
......
  server {
    location / {
    ......
    #Add control rule
    #Access denied client IP
    deny 192.168.133.31;
    #Allow other IP clients to access
    allow all;
    }
  }

systemctl restart nginx

VII Domain name based Nginx virtual host

1. Provide domain name resolution for virtual host

echo "192.168.133.10 www.test1.com www.test2.com" >> /etc/hosts

2. Prepare web documents for the virtual host

mkdir -p /var/www/html/test1
mkdir -p /var/www/html/test2
echo "<h1>www.test1.com</h1>" > /var/www/html/test1/index.html
echo "<h1>www.test2.com</h1>" > /var/www/html/test2/index.html

3. Modify the configuration file of Nginx

vim /usr/local/nginx/conf/nginx.conf
......
http {
......
    server {
        listen 80;
        server_name  www.test1.com;
        charset utf-8;
        access_log logs/www.test1.access.log;
        
        location / {
            root   /var/www/html/test1;
            index  index.html index.php;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
	}
	
     server {
         listen 80;
         server_name www.test2.com;
         charset utf-8;
         access_log logs/www.test2.access.log;
         
         location / {
              root /var/www/html/test2;
              index index.html index.php;
         }
         
         error_page 500 502 503 504 /50x.html;
               location = 50x.html{
               root html;
               }
         }
}


4. Restart the service and access the test

nginx -t
systemctl restart nginx


Browser access
http://www.test1.com
http://www.test2.com



VIII IP based Nginx virtual host

1. Add network card and domain name resolution

ifconfig ens33:0 192.168.133.100 netmask 255.255.255.0

echo "192.168.133.10 www.test1.com" >> /etc/hosts
echo "192.168.133.100 www.test2.com" >> /etc/hosts


2. Modify the configuration file of Nginx

vim /usr/local/nginx/conf/nginx.conf
......
http {
......
  server {
    listen 192.168.133.10:80;
    server_name  www.test1.com;
    charset utf-8;
    access_log logs/www.test1.access.log;
    location / {
      root   /var/www/html/test1;
      index  index.html index.php;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   html;
    }
  }
  server {
    listen 192.168.133.100:80;
    server_name www.test2.com;
    charset utf-8;
    access_log logs/www.test2.access.log;
    location / {
      root /var/www/html/test2;
      index index.html index.php;
    }
    error_page 500 502 503 504 /50x.html;
    location = 50x.html{
      root html;
    }
  }
}

3. Restart the service and access the test

systemctl restart nginx
#Browser access
http://192.168.133.10/
http://192.168.133.100/



IX Port based Nginx virtual host

vim /usr/local/nginx/conf/nginx.conf
......
http {
......
  server {
    listen 192.168.133.10:80;
    server_name  www.test1.com;
    charset utf-8;
    access_log logs/www.test1.access.log;
    location / {
      root   /var/www/html/test1;
      index  index.html index.php;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   html;
    }
  }
  server {
    listen 192.168.133.10:8080;
    server_name www.test2.com;
    charset utf-8;
    access_log logs/www.test2.access.log;
    location / {
      root /var/www/html/test2;
      index index.html index.php;
    }
    error_page 500 502 503 504 /50x.html;
    location = 50x.html{
      root html;
    }
  }
}	

systemctl restart nginx
 Browser access
http://192.168.133.10:8080
http://192.168.133.10:80