Location>code7788 >text

Nginx Basic Usage

Popularity:558 ℃/2024-12-19 21:55:58

Nginx

Nginx is a web service

1】、Install nginx

1.Official website installation
2. Use the default repository installation, the version is lower
3.Compile installation, when you need other functional modules Custom installation
# Installation based on official repositories, newer versions, easy to read configurations
# Prepare the repository
[root@web01 ~]# cat /etc//
[nginx-stable]
name=nginx stable repo
baseurl=/packages/centos/7/$basearch/
gpgcheck=1
enabled=1
gpgkey=/keys/nginx_signing.key
module_hotfixes=true

# Install nginx
[root@web01 ~]# yum install -y nginx
[root@web01 ~]# nginx -v
nginx version: nginx/1.26.1

Source code compilation and installation of nginx

Role: Customize the nginx installation configuration and required modules according to requirements

corresponds English -ity, -ism, -ization: Customize as needednginxInstallation configuration and required modules
1.Installation of dependencies
[root@lb01 ~]# yum install -y gcc glibc gcc-c++ pcre-devel openssl-devel patch

2.downloadingNginxsource code package(To be in line with the currentnginxThe version number is the same.) decompression (in digital technology)
[root@lb01 ~]# wget /download/nginx-1.26.
[root@lb01 ~]# tar xf nginx-1.26.

3.downloading第三方模块 decompression (in digital technology)
[root@lb01 ~]# wget /yaoweibin/nginx_upstream_check_module/archive/
[root@lb01 ~]# unzip

4.Adding new modules to the default template
[root@lb01 nginx-1.26.1]# patch -p1 < ../nginx_upstream_check_module-master/check_1.20.1+.patch

5.Add the location of the module to the default configuration
--add-module=/root/nginx_upstream_check_module-master

#############################
--prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/ --error-log-path=/var/log/nginx/ --http-log-path=/var/log/nginx/ --pid-path=/var/run/ --lock-path=/var/run/ --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --add-module=/root/nginx_upstream_check_module-master --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

Copy the module information above when you're done,Entering the first6a pace
6.Configuration Installation
[root@lb01 nginx-1.26.1]# ./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/ --error-log-path=/var/log/nginx/ --http-log-path=/var/log/nginx/ --pid-path=/var/run/ --lock-path=/var/run/ --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --add-module=/root/nginx_upstream_check_module-master --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'


compiling
[root@lb01 nginx-1.26.1]# make

8.mounting
[root@lb01 nginx-1.26.1]# make install


9.Inspection Module
[root@lb01 ~]# nginx -V
nginx version: nginx/1.26.1
built by gcc 7.3.0 (GCC)
built with OpenSSL 1.1.1f 31 Mar 2020
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/ --error-log-path=/var/log/nginx/ --http-log-path=/var/log/nginx/ --pid-path=/var/run/ --lock-path=/var/run/ --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --add-module=/root/nginx_upstream_check_module-master --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'


[root@lb01 ]# nginx -t
nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful

2], nginx configuration file parsing

/etc/nginx/
[root@web01 nginx]# cat
# Kernel blocks
user nginx; # User running nginx This user is created automatically when nginx is installed.
worker_processes auto; # Number of processes started by nginx, based on the kernel.

error_log /var/log/nginx/ notice; # Location of the error log.
pid /var/run/; # The pid number of nginx is written to this file.
#The events module
events {
    worker_connections 25532; # Maximum number of connections per process.
}


# http block Receives browser requests and responds to them.
http {
charset utf-8,gbk; # Supported encoding formats.
    include /etc/nginx/; # file types supported by the site
    default_type application/octet-stream; # If the site does not support the type, download it locally.

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      ' "$http_user_agent" "$http_x_forwarded_for"'; # Log format

    access_log /var/log/nginx/ main; # Location of access logs

    sendfile on; # File transfer
    #tcp_nopush on; # file transfer

    keepalive_timeout 65; # Long connections are automatically disconnected from the browser in 65 seconds.

    #gzip on; # whether to compress resources

    include /etc/nginx//*.conf; # Include *.conf in the current file.

}

The server block is included in the http block.
[root@web01 ~]# cat /etc/nginx//
[root@web01 ~]# > /etc/nginx//
[root@web01 ]# cat
server {
listen 80 ; # Port to listen on
server_name ; # Purchased domain name hosts resolution

location / { # path match /
root /code; # Let users go to the /code directory to get information about the site.
index ; # The file returned to the browser by default.
}
}

# Create the code directory
mkdir /code
# Upload website code, unzip to code directory
[root@web01 ~]# unzip -d /code/
[root@web01 ~]# ll /code/
total 48
-rw-r--r-- 1 root root 28032 May 24 2021 bgm.mp3
drwxr-xr-x 2 root root 23 May 24 2021 css
drwxr-xr-x 2 root root 23 May 24 2021 images
-rw-r--r-- 1 root root 8956 May 24 2021
drwxr-xr-x 2 root root 213 May 24 2021 js
drwxr-xr-x 2 root root 4096 May 24 2021 roms
-rw-r--r-- 1 root root 811 May 24 2021
# Client Access

HTTP 404 # Code directory does not exist
HTTP 403 # There is a code directory but no file

Log files.
/var/log/nginx/
/var/log/nginx/

2024/12/06 18:55:40 [error] 147450#147450: *14 open() "/code/aasdsadsa" failed (2: No such file or directory), client: 192.168.121.1, server: , request: "GET /aasdsadsa HTTP/1.1", host: ""
2024/12/06 18:55:41 [error] 147450#147450: *14 open() "/code/aasdsadsa" failed (2: No such file or directory), client: 192.168.121.1, server: , request: "GET /aasdsadsa HTTP/1.1", host: ""

3], nginx configuration multi-service

Based on multiple IP addresses Understanding
10.0.0.7----------->Ninja
10.0.0.8----------->Ze
1. Configure an ip address
[root@web01 ~]# ip add add 10.0.0.8/24 dev ens33

2. Configure the file to 10.0.0.7 corresponding to the ninja service
[root@web01 ]# cat
server {
listen 10.0.0.7:80; # Port to listen on.
server_name _; # Purchased domain name hosts resolution

location / { # Path match /
root /code; # Let users go to the /code directory to get information about the site.
index ; # The file returned to the browser by default.
}
}
[root@web01 ]# nginx -t
nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful
[root@web01 ]# systemctl restart nginx

3. Check the current listening ports
[root@web01 ]# netstat -tnulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 10.0.0.7:80 0.0.0.0:* LISTEN 32133/nginx: master


Increase the service of Xiaobajing Accessed through 10.0.0.8 IP address
1. Add server configuration
[root@web01 ]# cat
server {
listen 10.0.0.8:80;
server_name _;

location / {
root /game ;
root /game; index ;
}
}
2. Create the code directory
[root@web01 ]# mkdir /game
[root@web01 ]# cd /game/
3. Upload the game package
[root@web01 game]# ll
total 7708
-rw-r--r-- 1 root root 7890373 Dec 6 11:34
[root@web01 game]# unzip

4. Check the configuration file
[root@web01 game]# nginx -t
nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful


5. Restart nginx
[root@web01 game]# systemctl restart nginx

Browser access: 10.0.0.7--->Ninja
  10.0.0.8--->Ze
[root@web01 game]# netstat -tnulp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 10.0.0.8:80 0.0.0.0:* LISTEN 32233/nginx: master
tcp 0 0 10.0.0.7:80 0.0.0.0:* LISTEN 32233/nginx: master
Why is IP-based less used? Because most of the bandwidth nowadays is BGP multi-line. Instead of single line


Based on multiple ports Commonly used 80 is for users, the backend of their own business can not be accessed by users. Customize the port of the backend
10.0.0.7:80------>ninja
10.0.0.7:81------>LittleBully
Ninja configuration file
[root@web01 ]# cat
server {
listen 80; # Port to listen on
server_name _; # Purchased domain name hosts resolution

location / { # Path match /
root /code; # Let users go to the /code directory to get information about the site.
index ; # The file returned to the browser by default.
}
}

The Zeppelin configuration file
[root@web01 ]# cat
server {
listen 81;
server_name _;

location / {
root /game ;
index ;
}
}

[root@web01 ]# nginx -t
nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful
[root@web01 ]# systemctl restart nginx

Access test: 10.0.0.7
10.0.0.7:80
10.0.0.7:81





Based on multiple domains Commonly used
-------->ninja
-------->Ze
Configure the Ninja service
[root@web01 ]# cat
server {
listen 80 ; # Port to listen on
server_name ; # Purchased domain name hosts resolution

location / { # path match /
root /code; # Let users go to the /code directory to get information about the site.
index ; # The file returned to the browser by default.
}
}

Configure the Zeus game service
[root@web01 ]# cat
server {
listen 80 ; server_name ;
server_name ;

location / {
root /game ;
root /game ; index ;
}
}

[root@web01 ]# nginx -t
nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful
[root@web01 ]# systemctl restart nginx

Test access.
 Corresponding Ninjas
 The equivalent of Ze

❓ Difference between reload and restart

Generally speaking, if we have made changes to the original configuration file, use reload to take effect.

If a new configuration file is created, it takes effect with restart.

4], nginx common module

nginx configuration file partitioning

http zone

server area

location

1. auto_index index module

autoindex
on: indicates that the indexing module is turned on
off: disables the indexing module
autoindex_localtime
on: show file time as file server time
off: show the file time as the time of the file server.
autoindex_exact_size
on:show the exact size of the file in bytes
off: show the approximate size of the file in KB, GB or MB
# Create the configuration file for the indexing module
[root@web01 ~]# cat /etc/nginx//
server {
        listen 80 ;
        server_name ;
        autoindex on ;
        autoindex_localtime on; autoindex_exact_size off; autoindex_localtime on
        autoindex_exact_size off; autoindex_localtime on; autoindex_exact_size on
        location / {
                root /code/index ;
                index ;
        }
}
# Create the corresponding directory
[root@web01 ~]# mkdir /code/index/{01..10} -p

# Perform hosts resolution
192.168.121.7

access test

image-20241209143434287

[root@web01 ~]# cd /code/index/01
[root@web01 01]# echo `pwd` > 

image-20241209143535561

[root@web01 01]# cd /code/index/
[root@web01 index]# echo `pwd` > /code/index/

image-20241209143615311

We can then access the content on the page by way of a table of contents

2、Download Restriction Module

No speed limit by default, limit download speed

limit_rate 0
limit_rate_after 50M # Next 50M; no rate limit, start limiting after that
[root@web01 ~]# cat /etc/nginx//
server {
        listen 80;
        server_name ;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
        limit_rate 1M;
        location / {
                root /code/index;
                index ;
        }
}

image-20241209145318916

[root@web01 ~]# cat /etc/nginx//
server {
        listen 80;
        server_name ;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
        limit_rate 1M;
        limit_rate_after 10M;
        location / {
                root /code/index;
                index ;
        }
}

3. Based on the user login authentication module

Function: Username and password are required to log in to the website.

auth_basic off|string
auth_basic_user_file auth_conf
Generate password file
# -b Enter the password directly from the command line without interaction -c What it means to create a document
htpasswd -c -b /etc/nginx/ xu xu
[root@web01 ~]# cat /etc/nginx/
xu:$apr1$8k9aXaPG$JC2DrQ3C/Bsv9qPErDQaf/

2.configuration file
[root@web01 ~]# cat /etc/nginx//
server {
        listen 80;
        server_name ;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
        limit_rate 1M;
        limit_rate_after 10M;
        auth_basic "hahah";
        auth_basic_user_file ;
        location / {
                root /code/index;
                index ;
        }
}
[root@web01 ~]# systemctl reload
[root@web01 ~]# tail -1 /var/log/nginx/
192.168.121.1 - xu [09/Dec/2024:15:04:38 +0800] "GET / HTTP/1.1" 200 1309 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" "-"

image-20241209150725096

If there is a validation error when entering the password, the status code is 401

192.168.121.1 - xu [09/Dec/2024:15:07:18 +0800] "GET / HTTP/1.1" 401 581 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0" "-"

4. nginx state module

Purpose: Displays information about the user's connection to nginx.
stub_status # Can only be placed in server and location.
[root@web01 ~]# cat /etc/nginx// 
server {
        listen 80;
        server_name ;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
        limit_rate 1M;
        limit_rate_after 10M;
        auth_basic "hahah";
        auth_basic_user_file ;
        location / {
                root /code/index;
                index ;
        }
        location /nginx_status {
                stub_status;
        }
}

image-20241209151724228

# Current TCP connections
Active connections: 2

# accept: how many have been received
# handled: number of handled
# request: number of http requests
server accepts handled requests
 27 27 40

# Reading: number of request headers currently read
# Writing: number of request headers responded to
# Waiting: number of requests waiting, keepalived is enabled
Reading: 0 Writing: 1 Waiting: 1

5. IP Access Control Module

# What is allowed
allow address|CIDR|all

# What to reject
deny address|CIDR|all
[root@backup ~]# curl 192.168.121.7/nginx_status
Active connections: 1
server accepts handled requests
 46 46 59
Reading: 0 Writing: 1 Waiting: 0

# impermissible192.168.121.41interviewsnginx_status
[root@web01 ~]# cat /etc/nginx//
server {
        listen 80;
        server_name ;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
        limit_rate 1M;
        limit_rate_after 10M;
        location / {
                root /code/index;
                index ;
        }
        location /nginx_status {
                stub_status;
                allow 192.168.121.7; # limit/nginx_statusweb page,别的都能interviews
                deny all;
        }
}
[root@web01 ~]# curl 192.168.121.7/nginx_status
Active connections: 1
server accepts handled requests
 47 47 60
Reading: 0 Writing: 1 Waiting: 0
[root@backup ~]# curl 192.168.121.7/nginx_status
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.26.1</center>
</body>
</html>

6. Nginx access restrictions

This is often encountered in the enterprise, server traffic anomalies, excessive load and so on. For large traffic malicious attack access, it will bring the waste of bandwidth, server pressure, affecting the business, which will often consider the number of requests and connections to the same IP to limit.

The ngx_http_limit_conn_module module allows you to limit the number of connections per key value based on a defined key, such as the number of connections from the same IP source.

limit_conn_module Connection frequency limit

limit_req_module Request Frequency Limit

(1) TCP connection limit

limit_conn_module key zone=name:size
http
[root@web01 ~]# cat /etc/nginx// -
limit_conn_zone $remote_addr zone=conn_zone:10m;
#Restriction module name client (computing)IP The name of the open memory space is called conn_zone space size10m
server {
        listen 80;
        server_name ;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
        limit_rate 1M;
        limit_rate_after 10M;
        location / {
                limit_conn conn_zone 1; # limitationlimit_conn_zoneAll in spaceIP At the same time only1classifier for individual things or people, general, catch-all classifierTCPgrout
                root /code/index;
                index ;
        }
        location /nginx_status {
                stub_status;
                allow 192.168.121.7;
                deny all;
        }
}

(2) Limit on the number of requests

limit_req_zone $remote_addr zone=req_zone:10m rate=20r/s; # Maximum 20 requests per second
[root@web01 ~]# cat /etc/nginx//
limit_req_zone $remote_addr zone=req_zone:10m rate=20r/s; # Maximum per second20request
server {
        listen 80;
        server_name ;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
        limit_rate 1M;
        limit_rate_after 10M;
        location / {
                limit_req zone=req_zone burst=5 nodelay; # Limit delay processing5classifier for individual things or people, general, catch-all classifier,Remaining returns503
                root /code/index;
                index ;
        }
        location /nginx_status {
                stub_status;
                allow 192.168.121.7;
                deny all;
        }
}

【5】、Location matching rule prioritization

Matches Match Rule Priority
= Exact match 1
^~ Starts with a string 2
~ Case-sensitive regular matching 3
~* Case-insensitive regular match 4
/ Generic match, any request will match 5
server {
        listen 80;
        server_name ;
        default_type text/html;
        location ~ /haha {
                return 200 "configuration E";
        }
        location / {
                return 200 "configuration A";
        }
        location = / { 
                return 200 "configuration B";
        }
        location ^~ /document {
                return 200 "configuration C";
        }
        location ~* \.(jpg|gif)$ {
                return 200 "configuration D";
        }
}

image-20241209203818954

image-20241209203841040

image-20241209203929127

image-20241209203957264

【6】、rewrite

Rewrite mainly implements url address rewriting, as well as redirection, that is, the process of redirecting incoming web requests to other urls.

1、Address hopping, when the user visits this URL, it will be directed to a new domain name

2、Protocol jump, the user requests the site through the http protocol, it will be re-directed to the https protocol mode

3, pseudo-static, the dynamic page will be displayed as a static page way of a technology to facilitate the entry of search engines, while reducing the dynamic URL address to expose too many parameters to enhance the higher security.

4, search engine, SEO optimization depends on the url path, remember the url to facilitate the support of search engine entry

1. rewrite configuration

syntax:Syntax: rewrite regex replacement [flag]
default (setting):Default: --
context:Context: server,location,if

[root@web01 ]# cat
server {
        listen 80;
        server_name ;
        root /code/test;
        location / {
                rewrite / /;
                #rewrite / /;
        }
}

image-20241216153831686

2、flag setting

The rewrite directive redirects a URL or modifies a string according to an expression. It can be used in server, location, and if environments, and each line of the rewrite directive is followed by a flag flag at the end of the line, and the supported flag flags are shown in the following table:

flag corresponds English -ity, -ism, -ization
break After this rule has been matched, it stops matching and does not match the following rules
last After this rule is matched, it stops matching and does not match the following rules, but will re-initiate the request
redirect Returns a 302 temporary redirect, the address bar shows the address after the jump
permanent Return to 301 permanent redirect, the address bar displays the address after the jump
[root@web01 ]# cat 
server {
        listen 80;
        server_name ;
        root /code/test/;

        location / {
        rewrite / /;
        rewrite / /; 
        }

        location / {
        rewrite / /;
        }

        location / {
        rewrite / /;
        }
}
[root@web01 ]# echo  > /code/test/
[root@web01 ]# echo  > /code/test/
[root@web01 ]# echo  > /code/test/
[root@web01 ]# echo  > /code/test/

image-20241216160254471

image-20241216160311848

image-20241216160340463

# break Stop matching backward,Resources in Returns
[root@web01 ]# cat
server {
        listen 80;
        server_name ;
        root /code/test/;

        location / {
        rewrite / / break;
        rewrite / /;
        }

        location / {
        rewrite / /;
        }

        location / {
        rewrite / /;
        }
}

image-20241216160445441

# last: stops matching backwards, but the browser re-initiates the request to the server. The first time it matches /, then it re-initializes the / request, so it matches /
[root@web01 ]# cat
server {
        listen 80 ;
        server_name ;
        root /code/test/ ;

        location / {
        rewrite / / last;
        rewrite / /;
        }

        location / {
        rewrite / /;; }
        }

        location / {
        rewrite / /; }
        }
}

image-20241216160605857

# redirect 302Temporary redirection
[root@web01 ]# cat
server {
        listen 80;
        server_name ;
        root /code;

        location /test {
                rewrite ^(.*)$ redirect;
                #rewrite ^(.*)$ permanent;
                #return 301 ;
                #return 302 ;
        }
}

image-20241216161509074

# permanent 301Permanent redirect
[root@web01 ]# cat
server {
        listen 80;
        server_name ;
        root /code;

        location /test {
                #rewrite ^(.*)$ redirect;
                #return 302 ;
                rewrite ^(.*)$ permanent;
                #return 301 ;
        }
}
# Testing direct access and closurenginxaftercare,All can access to Baidu

image-20241216161809101

redirect: ask the server for each request, if when the server is unavailable, the jump fails.

permanent: The first request asks and the browser records the address to jump to, the second does not ask the server and jumps directly to the address cached by the browser.

Before writing a rewrite rule, we need to turn on rewrite logging to debug rule matches.

http {
	rewrite_log on;
}

Case 1: A user accessing /abc/ is actually accessing /ccc/bbb/.

[root@web01 ]# cat
server {
        listen 80;
	server_name ;
	root /code;
        location / {
                root /code;
                index ;
        }
        location /abc {
                rewrite (.*) /ccc/bbb/ redirect;
                #return 302 /ccc/bbb/;
        }
}




Regular Matching Method
[root@web01 ]# cat
server {
        listen 80;
	server_name ;
	root /code;
        location / {
                root /code;
                index ;
        }
        location ~ abc$ { # match withabcfinalurl
                rewrite (.*) /ccc/bbb/ redirect;
                #return 302 /ccc/bbb/;
        }
}

[root@web01 ]# cat
server {
        listen 80;
	server_name ;
	root /code;
        location / {
                root /code;
                index ;
        }
        location ~ ^/abc$ { # must beabc
                rewrite (.*) /ccc/bbb/ redirect;
                #return 302 /ccc/bbb/;
        }
}

[root@web01 ]# mkdir /code/ccc/bbb -p
[root@web01 ]# echo > /code/ccc/bbb/
[root@web01 ]# cat /code/ccc/bbb/

image-20241216164951667

Users accessing /2018/ccc/ are actually really accessing /2014/ccc/

[root@web01 ]# cat  
server {
        listen 80;
        server_name ;
        root /code;

        location  /2018 {
                rewrite ^/2018/(.*)$  /2014/$1 redirect;
        }
}

image-20241216165729182

[root@web01 ]# vim 
server {
        listen 80;
        server_name ;
        root /code;
        location / {
                root /code;
                index ;
        }

        location /2024 {
                rewrite ^/2024/(.*)-(.*).html$ /2018/$1/$2/ redirect;
        }
}                                                                                                          
"" 13L, 275C written                                                        
[root@web01 ]# ll /code/2018/
total 0
drwxr-xr-x 3 root root 16 Dec 16 10:00 11
[root@web01 ]# ll /code/2018/11/22/
total 4
-rw-r--r-- 1 root root 22 Dec 16 10:00 
[root@web01 ]# echo hehe > /code/2018/11/22/
[root@web01 ]# nginx -t
nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful
[root@web01 ]# systemctl restart nginx

image-20241216171249690

3、Error page jump

[root@web01 ]# cat  
server {
        listen 80;
        server_name ;
        root /code;

        location  /2018 {
                rewrite ^/2018/(.*)-(.*).html  /2014/$1/$2/ redirect;
        }
        error_page 403 404 500 501 502 @error_test;
        location @error_test {
                rewrite ^(.*)$ / break;
        }
}

image-20241216171957060

4、Use variables to determine the jump

# $args is the default variable in nginx, it is null by default and is assigned a value by the set command.
[root@web01 ]# cat
server {
    listen 80 ; server_name ;# server_name ;# server_name ;# server_name
    server_name ;
    set $args "&showoffline=1" ;
    location / {
    root /code ; index ; set $args "&showoffline=1"; location / {
    index ;
    }
    if ($remote_addr = 192.168.121.1 ){ # Determine if the client is 192.168.121.1 before performing the following rewrite
    rewrite (. *) $1; }
    }

}
[root@web01 ]# systemctl restart nginx
[root@web01 ]# curl
xixi

image-20241216173700564

Jump to maintenance page, specified IP normal access
[root@web01 ]# cat
server {
    listen 80; server_name ;
    server_name ;
    server_name ; root /code ;
    root /code ; index ;

    location / {
        set $ip 0; # Set variable to 0
        if ($remote_addr = "192.168.121.1"){
            set $ip 1; # Set to 1 if source IP is 0.1
        }
        if ($ip = 0){ # Determine if variable is 0 then jump to maintenance page
            rewrite ^(. *)$ / break;
        }
    }


}
[root@web01 ]# echo "The site is currently under maintenance ...." > /code/

image-20241216174831832

【8】、DNS hijacking

[root@web01 ]# cat
server {
         listen 80;
         server_name ;
         root /code/test;
         index ;
 }
[root@web01 ]# ll /code/test/

[root@web01 ]# cat /code/test/
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>I am.title</title>
</head>
<body>
<article>
  <header>
    <h1>I am.妹妹</h1>
    <p>Creation time:<time pubdate="pubdate">2025/5/20</time></p>
  </header>
  <p>
    <b>Aticle</b>First time I've used it.h5write an article,he's so good!*nervousness...
  </p>
  <footer>
    <p><small>all rights reserved (copyright statement)!</small></p>
  </footer>
</article>
</body>
</html>

image-20241216201924532

web02configuration hijacking
[root@web02 ]# cat
upstream jiechi {
        server 192.168.121.7:80;
}

server {
        listen 80;
        server_name ;

        location / {
                proxy_pass http://jiechi;
                proxy_set_header Host $http_host;
        }
}
# Modify site content directly
[root@web02 ]# cat
upstream jiechi {
        server 192.168.121.7:80;
}

server {
        upstream jiechi { server 192.168.121.7:80; } server {
        server_name ;

        location / {
                proxy_pass http://jiechi; proxy_set_header Host $http_host ; location / {
                proxy_set_header Host $http_host ;
sub_filter '<h1>I'm a sister' '<h1>hahaha ';;
                sub_filter '<b>Aticle</b>First time writing an article in h5, so damn nervous...' '<img src="/q_70/images03/20230828/">';';
                sub_filter '<small>All rights reserved' ' <small>open source ';
        }
}

image-20241216202046097

9], nginx performance optimization

1. Stress testing tools

In the system before the growth of business volume, we have to make appropriate preparations in case of a sudden increase in the volume of business brought about by the interface pressure, so for the interface stress test is very important, we first need to assess the system pressure, and then use the tool to detect the current system situation, whether it can meet the corresponding pressure requirements.

1.Installation of stress testing tools
[root@lb01 ~]# yum -y install httpd-tools

2.Using the stress test command ab
[root@web01 ~]# ab -n 200 -c 2 http://127.0.0.1/

#-n Number of requests to be executed
#-c Number of concurrent requests
#-k Whether to enable long connections,Not a long connection by default
# -p Specify the action to be tested,beget还bepost。。。。

[root@web01 ~]# ab -n20000 -c200 http://127.0.0.1/
This is ApacheBench, Version 2.3 <$Revision: 1874286 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, /
Licensed to The Apache Software Foundation, /

Benchmarking 127.0.0.1 (be patient)
Completed 2000 requests
Completed 4000 requests
Completed 6000 requests
Completed 8000 requests
Completed 10000 requests
Completed 12000 requests
Completed 14000 requests
Completed 16000 requests
Completed 18000 requests
Completed 20000 requests
Finished 20000 requests


Server Software: nginx/1.26.1 # Nginxversion number
Server Hostname: 127.0.0.1 # Host name of the pressure test
Server Port: 80 # Port number of the website

Document Path:          / # Specific resources for pressure testing
Document Length: 9 bytes # Total page size

Concurrency Level: 200 # concurrency
Time taken for tests:   1.498 seconds # Processing completion time
Complete requests: 20000 # Total number of requests
Failed requests:        0 # fail (e.g. experiments)
Total transferred:      5140000 bytes # Total page size Contains header data
HTML transferred:       180000 bytes # Page size
Requests per second: 13352.94 [#/sec] (mean) # throughput
Time per request: 14.978 [ms] (mean) # Average user request wait time
Time per request: 0.075 [ms] (mean, across all concurrent requests)
Transfer rate:          3351.28 [Kbytes/sec] received

Connection Times (ms)
              min mean[+/-sd] median max
Connect:        0 7 25.0 3 1050
Processing:     0 6 13.6 4 216
Waiting:        0 5 12.6 3 215
Total: 0 14 28.8 8 1061

Percentage of the requests served within a certain time (ms)
  50% 8
  66% 11
  75% 12
  80% 14
  90% 19
  95% 37
  98% 108
  99% 119
 100% 1061 (longest request)

2. File handles

Also called a file descriptor (maximum number of file opens)

File handle, Linux everything is a file, the file handle can be understood as an index, the file handle will be frequently increased with the call of our process, the system default file handle is limited, can not let a process unlimited calls, so we need to limit each process and each service to use how much file handle, file handle must be adjusted to optimize the parameters.

[root@web01 ]# ulimit -n
65535
[root@web01 ]# tail -1 /etc/security/
* - nofile 65535
1. System global modifications.
# * * represents all users
* soft nofile 25535
* hard nofile 25535

2. User localization modification
#For root user, soft only reminds, hard limits, nofile opens the maximum number of files
root soft nofile 65535
root hard nofile 65535

3. Process localization changes
# For nginx process, nginx comes with the configuration /etc/
worker_rlimit_nofile 30000
# Tweak kernel parameters to reuse time_wait state
[root@web01 ROOT]# vim /etc/
net.ipv4.tcp_tw_reuse = 1 # enable port reuse
net.ipv4.tcp_timestamps = 0 # disable timestamps
[root@web01 ROOT]# sysctl -p # You can view the kernel parameters we added
[root@web01 ROOT]# sysctl -a #You can see all kernel parameters

On TCP servers with highly concurrent short connections, the server actively closes the connection normally as soon as it finishes processing the request. This scenario results in a large number of sockets in the TIME_WAIT state. If the concurrency of the client continues to be high, some clients will show that they cannot connect. Let me explain this scenario. TIM_EWAIT occurs when a TCP connection is closed normally.

Why should we be concerned about this high concurrency short connection? There are two aspects to keep in mind:

  1. High concurrency allows the server to occupy a large number of ports within a short period of time at the same time, and the port has a range of 0 ~ 65535, not a lot, planing system and other here is a relatively long concept, such as taking a web page, a 1-second HTTP short connection to deal with the business, in the closing of the connection, the business has used the port will remain in the state of the TIMEWAIT a few minutes, and the other HTTP requests come is not able to occupy this port (occupying the pit does not pull the Xiang). These minutes, other HTTP requests come to the time is not able to occupy this port (occupying the pit does not pull Xiang). Using this business alone to calculate the utilization of the server will find that the server to do serious work and the port (resource) is hanging unavailable time ratio is 1: several hundred, a serious waste of server resources. (As an aside, if you consider server performance tuning from this point of view, the long connection service does not need to consider the TIMEWAIT state. At the same time, if you are very familiar with the server business scenarios, you will find that in the actual business scenarios, generally long connections corresponding to the business concurrency is not very high.

3. Proxy servers use long connections

Usually nginx as a proxy service, responsible for forwarding the user's request, then in the process of forwarding it is recommended to open HTTP long connection, used to reduce the number of handshakes, reduce server loss

[root@lb01 ]# vim  
upstream wp {
     server 172.16.1.7:80;
     server 172.16.1.8:80;
     keepalive 16;
}
server {

}

4, configure static page caching

Browser cache settings are used to improve site performance, especially news sites, images, once published, the possibility of change is very small, so we hope to be able to users visit once, the image cache in the user's browser for a long time. Browsers have their own caching mechanism, he is based on the HTTP protocol caching mechanism to achieve, in the HTTP protocol has a lot of header information, then the realization of the browser's cache will need to rely on special headers to carry out special verification with the server, such as Expires (http/1.0); Cache-control (http/1.1).

image-20241219152334769

image-20241219152347501

Browser cache expiration checking mechanism

image-20241219152447919

Last-Modified: the last modification time of the file on the server

Etag: file identification

Expires: the time at which the file expires in the local cache directory (specified by the server)

Cache-control: local cache directory, file expiration time (specified by the server expiration interval, generated by the browser based on the interval of the specific time)

[root@web01 ]# cat  
server {
        listen 80;
        server_name ;
                root /code;
        location / {
                index ;
        }
        location ~ .*\.(jpg|gif|png)$ {
        expires      7d;
        }
}

image-20241219152731006

The newly configured page does not want to be cached by the user, and wants the user to go to the source for every request.

        location ~ .*\.(js|css|html)$ {
          add_header Cache-Control no-store;
          add_header Pragma no-cache;
      }

5、Efficient file transfer

image-20241219155502259

sendfile Parameters


vim
...
sendfile on; # Enable this configuration for large files.
tcp_nopush on; # Large files turn on this configuration
tcp_nodelay on; # Enable this for small files.
...

If you are transferring large files

Open sendfile on

​ tcp_nopush on

If the number of small files is large

Turn on tcpnodelay on

6. Static resource compression

NginxEnabling compression of response messages before they are sent to the client and then transmitted saves bandwidth and increases the speed of the response to the client

However, if compression is performed, it will consume CPU, so we need to consider whether or not to compress the transmission

image-20241219160859410

[root@web01 ]# cat
server {
        listen 80;
        server_name ;
                root /code;
        location / {
                index ;
        }
	location ~ .*\.(txt|xml|html|json|js|css)$ {
        gzip on; # opensgziptransport
        gzip_http_version 1.1; # gzipreleases
        gzip_comp_level 5; # compression class,1constitute a minimum
        gzip_types text/plain application/json application/x-javascript application/css application/xml text/javascript;
    }
}

7、Anti-theft chain

1.Servers ready to steal the chain WEB01
[root@web01 ]# cat
server {
        listen 80;
        server_name ;
                root /code;
        location / {
                index ;
        }

	location ~ .*\.(jpg|png|gif) {
        gzip on;
        gzip_types image/jpeg image/gif image/png;
        gzip_comp_level 9;
        gzip_http_version 1.1;
    }
}
[root@web01 ]# cat /code/
<html>
	<head>
		    <meta charset="utf-8">
		        <title></title>
	</head>
	<body style="background-color:pink;">
		    <center><img src="/"/></center>
	</body>
</html>


2.Preparing the source stationWEB02
[root@web02 ]# cat
server {
        listen 80;
        server_name ;
                root /code;
        location / {
                index ;
        }
}

[root@web02 ]# nginx -t
nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful
[root@web02 ]# systemctl restart nginx

Upload a picture to/code
[root@web02 code]# ll
-rw-r--r-- 1 root root 438692 Dec 19 11:33

windows hostsanalyze
192.168.121.7
192.168.121.8

3.Access to the website

image-20241219182805019

4.existweb02Configure on to prevent chain theft
[root@web02 ]# cat
server {
        listen 80;
        server_name ;
                root /code;
        location / {
                index ;
        }
        location ~ .*\.(jpg|png|gif) {
         valid_referers none blocked *.;
         if ( $invalid_referer ) {
            return 403;
        }
}
}

[root@web02 ]# nginx -t
nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful
[root@web02 ]# systemctl restart nginx




# Specify the page or image to return to orhtmlweb page
[root@web02 ]# cat
server {
        listen 80;
        server_name ;
                root /code;
        location / {
                index ;
        }
        location ~ .*\.(jpg|png|gif) {
         valid_referers none blocked *.;
         if ( $invalid_referer ) {
            #return 403;
	    rewrite ^(.*)$ / break; # exist/code/Pictures prepared under
        }
}
}

image-20241219182825335

8、Cross-domain request

What is cross-domain access, when we visit a website through the browser, at the same time will be utilized to ajax or other ways, but also request b website, in this case there is a request for a page, the use of two domain names, this way for the browser is prohibited by default.

image-20241219182910254

So what does Nginx semantic cross-site access have to do with the browser, because the browser reads the Access-Control-Allow-Origin header, and if the server allows it, the browser doesn't intercept it.

1.Configuring cross-domain files
[root@web02 ]# cat
server {
        listen 80;
        server_name ;
        location / {
                root /code;
                index ;
        }
}

[root@web02 ]# nginx -t
nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful
[root@web02 ]# systemctl restart nginx

[root@web02 ]# cat /code/
<html lang="en">
<head>
        <meta charset="UTF-8" />
        <title>test (machinery etc)ajaxand cross-domain access</title>
        <script src="/jquery/2.1.4/"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
        $.ajax({
        type: "GET",
        url: "",
        success: function(data) {
                alert("sucess It worked.!!!");
        },
        error: function() {
                alert("fail!!,I can't get across.,I'm not allowed in.,have no other choice...!");
        }
        });
});
</script>
        <body>
                <h1>跨域访问test (machinery etc)</h1>
        </body>
</html>

windows analyze
192.168.121.8
192.168.121.7
直接访问test (machinery etc)

image-20241219184050839

existweb01Configure to allow cross-domain requests
[root@web01 ]# cat
server {
        listen 80;
        server_name ;
                root /code;
        location / {
                index ;
        }
	location ~ .*\.(html|htm)$ {
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
        }
}

nginx: the configuration file /etc/nginx/ syntax is ok
nginx: configuration file /etc/nginx/ test is successful
[root@web01 ]# systemctl restart nginx

image-20241219184104245

9. cpu affinity

CPU affinity (affinity) to reduce the frequent switching between processes to reduce performance loss, the principle of its implementation is to build the CPU core and Nginx work process binding mode, each worker process is fixed to the corresponding cpu execution, reducing the switching CPU cache miss, to get better performance.

image-20241219184146305

/etc/nginx/
...
worker_cpu_affinity auto;
...

10. nginx optimization summary

Interview Question: What has Nginx optimized?
1. CPU affinity, number of worker processes, adjusting the number of open files per worker process # mandatory
worker_cpu_affinity auto; worker_processes auto; worker_cpu_affinity auto
worker_processes auto; worker_cpu_affinity auto; worker_processes auto; worker_processes auto
worker_cpu_affinity auto; worker_processes auto; ulimit -n

2, use epool network model, adjust the maximum number of connections per worker process default is 1024 # must do
event {
use epool; worker_connections 10240; worker_connections
worker_connections 10240.
}

3. Efficient reading of files sendfile, nopush # Depends on the requirements.
# When transferring large files, it is best to turn on
sendfile on;
tcp_nopush on;
# Recommended to turn on when transferring a large number of small files
tcp_nodelay on;


4, file transfer real-time, nodealy # Depends on the requirements

5. enable tcp long connection, and long connection timeout time keepalived # Configure if there is load balancing
keepalived 16.


6. Enable file transfer compression gzip # Depends on requirements
gzip on
gzip_http_version 1.1;
gzip_comp_level 5.
gzip_types text/plain application/json application/x-javascript application/css application/xml text/javascript.


7、Enable static file expires cache # Depends on the demand Static file cache days N years
expires 7d

8. Hide nginx version number # Required
server_token off.

9, prohibit access via ip address, prohibit malicious domain name resolution, only allow domain name access # Must do Empty host header Access business with IP address


10, configure anti-theft links, and cross-domain access # Depends on the needs of the


11, anti-DDOS, cc attacks, limit concurrent connections to a single IP, and http requests # See requirements
limit_conn_zone $remote_addr zone=conn_zone:10m;
# limit module name client IP opening up the memory space called conn_zone space size 10m
location / {
                limit_conn conn_zone 1; # Limit all IPs in the limit_conn_zone space to 1 TCP connection at a time.
                root /code/index ;
                index ;
        }

limit_req_zone $remote_addr zone=req_zone:10m rate=20r/s; # Maximum 20 requests per second.
 location / {
                limit_req zone=req_zone burst=5 nodelay; # Limit delay to 5, return 503 for the rest.
                root /code/index ;
                index ;
        }

12. Elegantly display the nginx error page # Depends on the requirement
error_page 403 404 500 501 502 @error_test ;
        location @error_test {
                rewrite ^(. *)$ / break; }
        }

13. nginx encrypted transmission https optimization # Must do
ssl_certificate ssl_key/;;
ssl_certificate_key ssl_key/;;