foreword

Why understand nginx?

  • First, improve your server deployment capabilities
  • Second, it helps to understand the backend interface link

What can ngix do?

  1. Solve cross-domain problems
  2. load balancing
  3. static server
  4. Multi/Single Page Website
  5. gzip

text

Installation & common commands & nginx configuration file structure

Installation (take ubuntu as an example):

 $ sudo apt-get install nginx

More: Install NGINX

View version:

 $ sudo nginx -v
# 出现版本信息表示安装成功
nginx version: nginx/1.6.2

Common commands

Start the service:

 $ nginx

Other commands:

 $ nginx -s <SIGNAL>

SIGNAL:

  • quit - gracefully shuts down the service
  • reload - reload the configuration file to run
  • reopen – open the log file
  • stop - stop the service immediately

configuration file

file structure

The main configuration file for nginx is nginx.conf. You can include configuration files in other locations in the main configuration file.
Installed in the above way:

  • Default configuration file path /etc/nginx/nginx.conf
  • There may be references in this file, such as include /etc/nginx/conf.d/*.conf; then in fact your project configuration file is all the .conf files in the /etc/nginx/conf.d/ folder;
  • Generally, a project (domain name) is equipped with a file. For example, your domain name is www.baidu.com, then your configuration file can be called /etc/nginx/conf.d/www.baidu.com.conf -
Configuration instructions

image.png

  • main: The global configuration of nginx, which takes effect globally.
  • events: The configuration affects the nginx server or the network connection to the user.
  • http: You can nest multiple servers, configure proxies, caches, log definitions, and other functions and configuration of third-party modules.
  • mail: Mailbox service configuration
  • stream: TCP and UDP configuration
  • server: Configure the relevant parameters of the virtual host. There can be multiple servers in one http.
  • location: Configure the routing of requests and the processing of various pages.
  • upstream: Configure the specific address of the back-end server, an indispensable part of the load balancing configuration.

resolve cross domain

If the interface for fe.server.com to access be.server.com is cross-domain, you can:

 http{
   server {
        server_name  fe.server.com;
        listen 80;
        location /api {
            proxy_pass fe.server.com/api;
        }
    }
}

Http load balancing

Load balancing strategy: https://zhuanlan.zhihu.com/p/89356016

  • Round-robin (default): time-sequentially assigned to different backend servers one by one
  • Specify weight: weight is proportional to the access ratio
  • fair: Allocate requests according to the response time of the backend server, and those with short response times will be given priority.
  • IP Hash: Assigned according to the hash result of visiting ip, so that each visitor has a fixed access to a backend server
  • Url Hash: Allocate requests according to the hash result of accessing the url, so that each url is directed to the same back-end server, which is more effective when the back-end server is cached.

Configure upstream:

 http{
  upstream balanceServer {
    server 10.1.22.33:12345;
    server 10.1.22.34:12345;
    server 10.1.22.35:12345;
  }
}

Configure the server:

 http{
   server {
        server_name  fe.server.com;
        listen 80;
        location /api {
            proxy_pass http://balanceServer;
        }
    }
}

More:

static server

/data/static/ Provide directory browsing:

 server{
  listen 80 default_server; 
  server_name www.example.com;

  location ^~ /static {
    root /data/static/; # 设置访问服务器下的文件目录
    autoindex on; # 开启目录浏览
    access_log  off; # 关闭访问日志
    charset utf-8,gbk;     #防止中文目录出现乱码
    expires     10h;# 设置过期时间为10小时
  }       
}

Mainly used autoindex on; open directory browsing See more: nginx open directory browsing function and theme beautification

single page website

  server {
        server_name  fe.server.com;
        listen 80;
        location / {
            root /data/www;
            index index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
    }
  • root: The file/directory address to be returned by the server
  • index: If the path ends with '/', index the files in the root directory in the order specified by index
  • try_files: The parsing order of root, first as a file, then as a folder, if neither exists, return /index.html file

location url matching rules

 
location [=|~|~*|^~|@] /uri/ {
  ...
} 
  • = : indicates an exact match of the following url
  • ~ : Indicates regular matching, but case-sensitive
  • ~* : Regular match, case insensitive
  • ^~ : Indicates common character matching, if this option matches, only this option is matched, not other options, generally used to match directories
  • @ : "@" defines a named location, used when targeting internally, such as error_page

The priority matching order of the above matching rules:

  1. = prefixed directives strictly match this query. If found, stop searching ;
  2. ^~ prefixed directives strictly match this query. If found, the search stops ;
  3. Regular expressions, related to the order defined in the configuration file, take the first matching content;
  4. All remaining regular strings, the longest match.

More: url matching rules

multi-page website

  server {
        server_name  fe.server.com;
        listen 80;
        location ^~ /app {
            root /data/www/app;
            index index.html index.htm;
            try_files $uri $uri/ /index.html;      
        }
        location ^~ /pc {
            root /data/www/pc;
            index index.html index.htm;
            try_files $uri $uri/ /index.html;      
        }
        location ^~ /api {
            # 指向 端口8080的 api 服务
            proxy_pass: https://fe.server.com:8080/api  
        }
        location / {
            root /data/www/html;
            index index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
    }

Precautions:

  • location / should be written at the end, as an option for the bottom line
  • root should be written in each location
  • The api is applied to other local ports, and the load balancing (server IP + port) is available for personal testing [New in 2022.01.27]

Gzip

HTTP compression using Gzip improves transfer speed and bandwidth utilization.

     gzip                    on; 
    gzip_http_version       1.1;        
    gzip_comp_level         5;
    gzip_min_length         1000;
    gzip_types text/csv text/xml text/css text/plain text/javascript application/javascript application/x-javascript application/json application/xml;
  • gzip: decide whether to enable the gzip module, on means open, off means close;
  • gzip_http_version: Identify the version of the http protocol. In the early days, browsers may not support gzip self-extracting, and users will see garbled characters.
  • gzip_comp_level: Set the gzip compression level, the lower the level, the faster the compression speed, the smaller the file compression ratio, and vice versa, the slower the file compression ratio; the level 1-9, the smallest compression is the fastest but consumes CPU
  • gzip_min_length: Set the minimum bytes of the page allowed to be compressed (obtained from the Content-Length of the header header). When the returned content is greater than this value, gzip will be used for compression. The unit is K. When the value is 0, all pages will be compressed. to compress. It is recommended to be greater than 1k
  • gzip_types: Set the MIME type that needs to be compressed, the non-set value will not be compressed, that is, match the compression type

deploy https

https://cloud.tencent.com/document/product/400/35244
https requires 1.ssl_certificate: crt certificate file on port 443; 2.ssl_certificate_key: key private key file. Put it in the nginx folder and create a new ssl.conf file in the conf.d folder

 # 以部署 cloud.tencent.com 为例子
# 证书: 1_cloud.tencent.com_bundle.crt
# 私钥: 2_cloud.tencent.com.key
server {
        #SSL 访问端口号为 443
        listen 443 ssl; 
        #填写绑定证书的域名
        server_name cloud.tencent.com; 
        #证书文件名称
        ssl_certificate 1_cloud.tencent.com_bundle.crt; 
        #私钥文件名称
        ssl_certificate_key 2_cloud.tencent.com.key; 
        ssl_session_timeout 5m;
        
        #请按照以下协议配置
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; 
        #请按照以下套件配置,配置加密套件,写法遵循 openssl 标准。
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; 
        ssl_prefer_server_ciphers on;
        
        location / {
           #网站主页路径。此路径仅供参考,具体请您按照实际目录操作。
           #例如,您的网站运行目录在/etc/www下,则填写/etc/www。
            root html; 
            # 此处不用修改
            index  index.html index.htm;
        }
    }

http redirect to https

http on port 80
http://cloud.tencent.com -> https:cloud.tencent.com

 server {
    listen 80;
    #填写绑定证书的域名
    server_name cloud.tencent.com; 
    #把http的域名请求转成https
    return 301 https://$host$request_uri; 
}
  1. nginx built-in variables
    $host: domain name
    $request_uri: remove the remaining part of the first $host from the complete url
  2. 301 Jump

enable http2

For more information, please refer to: How to upgrade a website to http/2
Require:

  • The minimum version of nginx is 1.10.0
  • The minimum version of openssl is 1.0.2

Modify the nginx configuration, the original https listen is:

 listen 443 ssl;

Now add http2 after:

 listen 443 ssl http2;

Reference article


specialcoder
2.2k 声望170 粉丝

前端 设计 摄影 文学