Moonlit Torii

Nginx Deployment

Nginx from zero: installation, site configuration, reverse proxy, HTTPS, and deployment issues.

01 One article to understand nginx deployment without asking for help

What is nginx

Nginx (engine x) is a high-performance HTTP and reverse proxy web server

Nginx is a lightweight web server/reverse proxy server. It is very powerful in handling high concurrency, and supports hot deployment. It is easy to start and can run 7*24 uninterruptedly.

Positive generation and counter-generation

The most important thing to learn nginx is reverse proxy

Figure 1 for Positive generation and counter-generation

Figure 2 for Positive generation and counter-generation

Install nginx

Direct installation

Beginners can try this mode

Bash
yum install -y nginx

docker installation

Bash
docker pull nginx:latest

docker run -itd --name nginx -p 80:80 nginx:latest

If you use docker, you can map the configuration files and directories to facilitate modifications.

Common commands

Bash
# 开启服务
nginx

# 快速停止
nginx -s stop

# 有序停止
nginx -s quit

# 重启服务:
nginx -s reload

# 检查配置文件是否有语法操作
nginx -t

nginx.conf

nginx default configuration file

Usually in /usr/local/nginx/conf/nginx.conf

nginx.conf consists of multiple blocks. The outermost block is main. Main contains Events and HTTP. HTTP contains upstream and multiple servers. Server contains multiple locations.

nginx
user  nginx;  # 指定nginx进程的运行用户
worker_processes  auto; # 指定Nginx要开启的进程数,每个Nginx进程平均耗费10M~12M内存。建议指定和CPU的数量一致即可。

error_log  /var/log/nginx/error.log notice; # 用来定义全局错误日志文件。日志输出级别有debug、info、notice、warn、error、crit可供选择,其中,debug输出日志最为最详细,而crit输出日志最少。
pid        /var/run/nginx.pid; # 用来指定进程pid的存储文件位置


events {
    worker_connections  1024;  # 用于定义Nginx每个进程的最大连接数,默认是1024
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;   # 这里设定默认类型为二进制流,也就是当文件类型未定义时使用这种方式,例如在没有配置PHP环境时,Nginx是不予解析的,此时,用浏览器访问PHP文件就会出现下载窗口。

    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  /var/log/nginx/access.log  main;

    sendfile        on; # 用于开启高效文件传输模式。将tcp_nopush和tcp_nodelay两个指令设置为on用于防止网络阻塞;

    keepalive_timeout  65;  # 设置客户端连接保持活动的超时时间。在超过这个时间之后,服务器会关闭该连接;


    include /etc/nginx/conf.d/*.conf;  # 导入其他的配置文件,注意include所在的位置
}

main (global settings), server (host settings), upstream (load balancing server settings) and location (URL matches settings for a specific location).

  • The instructions set by the main block will affect all other settings;
  • The instructions of the server block are mainly used to specify the host and port;
  • The upstream command is mainly used for load balancing and setting up a series of back-end servers;
  • location block is used to match web page location.

localtion

URL address matching is the most flexible part of Nginx configuration. Location supports regular expression matching and conditional judgment matching. Users can use the location directive to implement Nginx filtering of dynamic and static web pages.

Figure 1 for localtion

I have prepared an html file here, and the html file introduces images

Then the configuration file is as follows:

nginx
server {
    listen 80;

    location / {
        root /opt/nginx_study/html; # 根目录
        index index.html; # 默认显示的页面
    }
}

At this time, you can see the pages and pictures normally by accessing the server IP.

Note that introducing images in html is a relative path. If you write like this

nginx
<img src="/html/image/1.jpg" alt="">
<img src="/html/image/2.jpg" alt="">

Can pictures be seen on the page without changing nginx?

The answer is yes, definitely not visible

Then we can configure the access path of the image

nginx
server {
    listen 80;

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
        root /opt/nginx_study;
    }

    location / {
        root /opt/nginx_study/html; # 根目录
        index index.html; # 默认显示的页面
    }
}

or

nginx
server {
    listen 80;

    location /html/ { # 后面没有/就会重定向
        root /opt/nginx_study;
        index image/1.jpg;  # 直接访问这个路径,会显示这个图片
    }
    location / {
        root /opt/nginx_study/html; # 根目录
        index index.html; # 默认显示的页面
    }


}

alias

There are two ways to configure file paths in Nginx, one is root and the other is alias

For example, in a project, there are two html files that need to be configured with routing to access them.

Table of contents is as follows

nginx
html
    html1
       index.html
    html2
       index.html

What I want to achieve is to access 127.0.0.1:80 by accessing index.html under html1

To access 127.0.0.1:80/xxx is to access index.html under html2

If you write like this, you will find that /xxx/ cannot reach /html2.

nginx
server {
    listen 80;

    location / {
        root /opt/nginx_study/html/html1;
        index index.html;
    }
     location /xxx/ {
        root /opt/nginx_study/html/html2/;  # 会把/xxx/的路径拼接上
        index index.html;
    }
}

So there is a path alias

This will solve the problem

nginx
server {
    listen 80;

    location / {
        root /opt/nginx_study/html/html1;
        index index.html;
    }
     location /xxx/ {
        alias /opt/nginx_study/html/html2/;  # 只会把/xxx/后面的路径拼接过来
        index index.html;
    }
}

Domain name configuration

server_name

If your project is accessed using IP, you don’t need to write this.

But if you have many services running on your server and want to use port 80 to access them

Then use domain name

Access different services by accessing different Subdo Name

Prepare three directories to facilitate access by three subdomains

Figure 1 for Domain name configuration

Because the demonstration is in an intranet environment, there is no real domain name available.

So we can only modify the visitor's hosts file and execute the above three domain names to the target server.

For example, my current hosts file

Bash
192.168.100.185 doc.fengfengzhidao.com
192.168.100.185 news.fengfengzhidao.com
192.168.100.185 video.fengfengzhidao.com

Then configure the nginx configuration file

nginx
server {
    listen 80;
    server_name doc.fengfengzhidao.com;

    location / {
        root /opt/nginx_study/html/doc.fengfengzhidao.com;
        index index.html;
    }
}
server {
    listen 80;
    server_name news.fengfengzhidao.com;

    location / {
        root /opt/nginx_study/html/news.fengfengzhidao.com;
        index index.html;
    }
}
server {
    listen 80;
    server_name video.fengfengzhidao.com;

    location / {
        root /opt/nginx_study/html/video.fengfengzhidao.com;
        index index.html;
    }
}

test

Bash
C:\Users\枫枫>curl http://doc.fengfengzhidao.com
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
doc.fengfengzhidao.com
</body>
</html>


C:\Users\枫枫>curl http://news.fengfengzhidao.com
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
news.fengfengzhidao.com
</body>
</html>


C:\Users\枫枫>curl http://video.fengfengzhidao.com
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
video.fengfengzhidao.com
</body>
</html>

Other matching patterns

The wildcard character "*" is supported in server_name, but it should be noted that the wildcard character cannot appear in the middle of the domain name, but can only appear in the first or last paragraph.

Regular expressions can be used in server_name, and ~ is used as the start mark of the regular expression string

On some blog sites, users will get their own exclusive blog after creating a blog. We can use wildcards to achieve this modification.

nginx
server {
    listen 80;
    server_name *.bolg.fengfengzhidao.com;

    location / {
        root /opt/nginx_study/html/doc.fengfengzhidao.com;
        index index.html;
    }
}

You can also use regular expressions

In this way, only zhangsan lisi wangwu can visit

nginx
server {
    listen 80;
    server_name ~^(zhangsan)|(lisi)|(wangwu).bolg.fengfengzhidao.com$;

    location / {
        root /opt/nginx_study/html/doc.fengfengzhidao.com;
        index index.html;
    }
}

Of course, the front end must obtain the current subdomain name, and then send it to the back end to query whether there is this user.

Our hosts file

nginx
192.168.100.185 blog.fengfengzhidao.com
192.168.100.185 zhangsan.blog.fengfengzhidao.com
192.168.100.185 lisi.blog.fengfengzhidao.com
192.168.100.185 wangwu.blog.fengfengzhidao.com
192.168.100.185 fengfeng.blog.fengfengzhidao.com

Certification

Figure 1 for Certification

You can often see this kind of web page that you need to enter your username and password to access.

How is this effect achieved?

Use htpasswd to generate a specific password file

nginx
yum install httpd-tools -y

Here I take test user with password 123456 as an example.

nginx
htpasswd -c  /opt/nginx_study/auth/htpasswd  test

Figure 2 for Certification

nginx configuration authentication

nginx
server {
    listen 80;

    location / {
      # 开启功能模块,关闭为off
        auth_basic on;
        # 指定密码配置文件
        auth_basic_user_file /opt/nginx_study/auth/htpasswd;
        root /opt/nginx_study/html; # 根目录
        index index.html; # 默认显示的页面
    }

}

If you use curl to access

nginx
curl -u test:123456 http://127.0.0.1

proxy_pass

This is the highlight of nginx, nginx agent

Generally, it is proxied to the back-end server for a specific route.

For example, I wrote a program here to match all paths and then print them out.

Go
package main

import (
  "encoding/json"
  "flag"
  "fmt"
  "github.com/gin-gonic/gin"
)

var name *string

// handler
func handler(c *gin.Context) {
  byteData, _ := json.Marshal(c.Request.Header)
  fmt.Println(string(byteData))
  c.String(200, fmt.Sprintf("%s %s name:%s", c.Request.URL.Path, c.ClientIP(), *name))
  return
}

func main() {
  addr := flag.String("addr", ":8080", "addr")
  name = flag.String("name", "default", "name")
  flag.Parse()
  router := gin.Default()
  router.GET("", handler)
  fmt.Println("服务运行中...")
  fmt.Printf("服务运行在:%s \n", *addr)
  router.Run(*addr)
}


build.bat

Vue
set GOOS=linux
go build -o main
set GOOS=windows

Then put the compiled file on the server and run it

Then configure proxy_pass

nginx
server {
    listen 80;

    location /a1/ {  # 匹配/a1/开始,将/a1/之后的加到/之后
        proxy_pass http://127.0.0.1:8080/;
    }
    location /a2/ {   # 匹配/a2/开始,将匹配的路径加到/之后,直观感受就是把被匹配的路径加上了
        proxy_pass http://127.0.0.1:8080;
    }
    location /b1/ {
        proxy_pass http://127.0.0.1:8080/xxx/;
    }
    location /b2/ {
        proxy_pass http://127.0.0.1:8080/xxx;
    }
}

The path here will have absolute path and relative path. It will be clear after a demonstration.

Bash
请求路径                              实际到后端的路径
/a1/                                     /
/a1/123                                  /123

/a2/                                     /a2/
/a2/123                                  /a2/123

/b1/                                     /xxx/
/b1/123                                  /xxx/123

/b2/                                     /xxx
/b2/123                                  /xxx123

Carry original ip

At this time, you will find that I request the server IP of 192.168.100.185

But the IPs received inside the service are all 127.0.0.1. Why is this?

We all know that nginx's proxy is a proxy that proxy the source user's request to the target server, that is, the requester becomes nginx

We only need to proxy the characteristics of the source request's identifying IP together with it.

Just configure a special request header.

nginx
server {
    listen 80;
    # proxy_set_header X-Real-IP $remote_addr; # 加在这里也可以

    location /a1/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://127.0.0.1:8080/;
    }
}

Load balancing

One of the application scenarios of nginx is load balancing. When there is a large number of visits, multiple requests can be distributed to multiple servers through load balancing, which is equivalent to handing over the load that one server needs to bear to multiple servers, thereby improving the throughput rate of the system; in addition, if one of the servers hangs up, other servers can still provide services normally, thereby improving the scalability and reliability of the system.

Start two services on the backend

nginx
./main -addr 127.0.0.1:8080 -name s1
./main -addr 127.0.0.1:8081 -name s2

nginx
upstream myapp1 {
  server 127.0.0.1:8080;
  server 127.0.0.1:8081;
}


server {
    listen 80;

    location /api/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://myapp1/;
    }
}

Then access the server ip:80/api/

You will find that the requests are sent to different backend services.

At this time, their weights are the same

nginx provides us with different weight modes

Polling (Nginx comes with it, default)

This strategy is Nginx's default load balancing strategy. Each client request is assigned to different servers in turn in chronological order. If the back-end service is unavailable, it will be automatically filtered out.

weight weight (Nginx comes with it)

nginx
upstream myapp1 {
  server 127.0.0.1:8080 weight=1;  # 打中的比例是 1/3
  server 127.0.0.1:8081 weight=2;  # 打中的比例是 2/3
}

ip_hash (Nginx comes with it)

ip_hash allocates each request according to the hash result of the access IP. This method can ensure that the same user will always access a back-end server. Advantages: It can guarantee the session and solve the problem that the session cannot be shared between servers.

nginx
upstream myapp1 {
  ip_hash;
  server 127.0.0.1:8080;
  server 127.0.0.1:8081;
}


server {
    listen 80;

    location /api/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://myapp1/;
    }
}

least_conn (Nginx comes with it)

Forward requests to backend servers with fewer connections. The configuration of each backend server may be different, and the requests processed may also be different. The requests processed may be faster or slower. least_conn dynamically selects a server with fewer connections to handle the current request based on the connection status of the backend server.

nginx
upstream myapp1 {
    least_conn;
  server 127.0.0.1:8080;
  server 127.0.0.1:8081;
}


server {
    listen 80;

    location /api/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://myapp1/;
    }
}

nginx restrictions

Blacklist

The blacklist function of nginx can intercept malicious IP directly at the nginx level so that it cannot reach the back-end service.

This is the effect after being intercepted

Figure 1 for Blacklist

Its configuration is also very simple

nginx
server {
    listen 80;
#     deny 192.168.100.113;  # 可以放在 server块

    location / {
        root /opt/nginx_study/html/;
        index index.html;
    }

    location /yyy/ {
        deny 192.168.100.113; # 也可以放在location块中
        alias /opt/nginx_study/html/;
        index index.html;
    }
}

The configuration of deny is not picky and can be placed in different scopes.

You can also use a dedicated file to store the blacklist, just include it in different places, as follows

black.conf

nginx
deny 192.168.100.113;

nginx.conf

nginx
server {
    listen 80;

    location / {
        root /opt/nginx_study/html/;
        index index.html;
    }

    include /opt/nginx_study/black.conf;
}

Whitelist

allow, usually used together with deny

As follows, only 192.168.100.113 access is allowed, and other IP access is denied.

nginx
server {
    listen 80;

    allow 192.168.100.113;
    deny all;

    location / {
        root /opt/nginx_study/html/;
        index index.html;
    }
}

UA blacklist

nginx
map $http_user_agent $bad_user_agent {
        default         0;
        ~*curl           1;
        ~*wget           1;
        ~*Unicornscan    1;
        ~*sqlmap         1;
        ~*nessus         1;
        ~*netsparker     1;
    }

server {
    listen 80;

     if ($bad_user_agent) {
        return 404;
    }

    location / {
        root /opt/nginx_study/html/;
        index index.html;
    }
}

Note that this map can only be written outside the server

At this point, direct access through curl will get 404

nginx
C:\Users\枫枫>curl 192.168.100.185
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.13.7</center>
</body>
</html>


C:\Users\枫枫>curl --user-agent sss 192.168.100.185
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
你会
</body>
</html>

Referer blacklist

nginx
map $http_referer $bad_referer {
        default         0;
        ~*evil\.com     1;
        ~*xxx\.com      1;
        ~*yyy\.com      1;
    }

server {
    listen 80;

     if ($bad_referer) {
        return 404;
    }

    location / {
        root /opt/nginx_study/html/;
        index index.html;
    }
}
nginx
C:\Users\枫枫>curl 192.168.100.185
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
你会
</body>
</html>


C:\Users\枫枫>curl -e xxx.com 192.168.100.185
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.13.7</center>
</body>
</html>

Request frequency blacklist

Hackers can simulate various attacks by sending a large number of requests. After the requests sent within a certain period of time reach a certain threshold, they will be judged as malicious requests. Implementing request frequency limit is also an application scenario of blacklist

Here is an example of requesting 5 times in one minute

nginx
limit_req_zone $binary_remote_addr zone=perip:10m rate=5r/m;


server {
    listen 80;

    limit_req zone=perip burst=5 nodelay;

    location / {
        root /opt/nginx_study/html/;
        index index.html;
    }
}

Here is an example of requesting 5 times in one second

nginx
limit_req_zone $binary_remote_addr zone=perip:10m rate=5r/s;


server {
    listen 80;

    limit_req zone=perip burst=10 nodelay;  # 最多可以处理10个并发请求

    location / {
        root /opt/nginx_study/html/;
        index index.html;
    }
}

https configuration

Self-signed ssl certificate

Bash
openssl genrsa -out private.key 2048
openssl req -new -key private.key  -out cert.csr
openssl x509 -req -in cert.csr -out cacert.pem -signkey private.key

nginx
server {
    listen 443 ssl;
    ssl_certificate /opt/nginx_study/ssl/cacert.pem;  # pem的路径
    ssl_certificate_key /opt/nginx_study/ssl/private.key;  # key的路径

    location / {
        root /opt/nginx_study/html/;
        index index.html;
    }
}

Because it is self-signed, the browser will prompt that it is unsafe, which is normal.

Figure 1 for Self-signed ssl certificate

SSL certificate of cloud platform

Place the key and pem files on the server

nginx
server {
    listen 80;  # 将80的请求重定向到443上去
    server_name www.xxx.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate /www/server/nginx/www.xxx.com.pem;  # pem的路径
    ssl_certificate_key /www/server/nginx/www.xxx.com.key;  # key的路径
    server_name www.xxx.com;

    location / {
        uwsgi_pass   127.0.0.1:8000;  # 这个案例是uwsgi的案例
        include uwsgi_params;
     }

    location /static {
        alias  /www/wwwroot/flask_deploy/static;
    }
}

gzip configuration

This configuration is not picky either.

nginx
server {
    listen 80;

    location / {
        gzip on;
        gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
        root /opt/nginx_study/html/;
        index index.html;
    }

     location /xxx/ {
        alias /opt/nginx_study/html/;
        index index.html;
    }
}

Figure 1 for gzip configuration

Figure 2 for gzip configuration

Reference documentation

Official website: http://nginx.org/

Detailed explanation of nginx: https://blog.csdn.net/hyfsbxg/article/details/122322125

Common nginx command operations: https://blog.csdn.net/lzfaq/article/details/129354700

Learn about nginx in 8 minutes: https://zhuanlan.zhihu.com/p/34943332

Common nginx commands and summary: https://www.cnblogs.com/ministep/p/15967012.html

nginx configuration file: https://blog.csdn.net/shenxiaomo1688/article/details/105858118

nginx load balancing: https://baijiahao.baidu.com/s?id=1745000622299474787&wfr=spider&for=pc

nginx server_name: https://blog.csdn.net/congge_study/article/details/124907421

nginx blacklist: https://www.php.cn/faq/557447.html

nginx request frequency limit: https://www.python100.com/html/109613.html

nginx gzip: https://blog.csdn.net/qq_35222232/article/details/132208282

nginx gzip specific configuration: https://blog.csdn.net/weixin_54931703/article/details/120814273