• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

  • nginxMore or less, some developers (e.g., back-end, operations) often come into contact with them. For front-end people, they may not know much about them, so this article will take you through and get startednginx.

What is thenginx

  • Baidu Encyclopedia nginx
  • nginxIs alightweightWebServer /The reverse proxyThe server andE-mail(IMAP/POP3) proxy server;
  • nginxCan be used as aHTTPThe server handles the publishing process of the website, in additionnginxIt can be used as a reverse proxy to implement load balancing.

The characteristics of

  • Free, open source, high performance, stability, rich feature set, simple configuration files and low system resource consumption.

Download and install

  • Nginx Download

WindowsThe installation
  1. Locate the downloaded zip file and unzip it
  2. Start thenginx(1) Double-clicknginx.exe, double-click after a black pop-up window flashed by (2) opencmdCommand window and switch tonginxDecompress the package in the directory (for example:C: \ Users \ Admin \ Downloads \ nginx - 1.20.1), enter the commandnginx.exeorstart nginx, press Enter.
  3. checknginxCheck whether the startup is successful.
    • Enter the url in the browser address barhttp://localhost:80Press Enter. If the following page is displayed, the startup is successful.

MacThe installation
  • useBrewThe installation,Install the Brew.
  • Check whether it has been installednginx
brew search nginx
Copy the code

  • Install if no
brew install nginx
Copy the code
  • Installation position
Nginx /usr/local/etc/nginx/ config file /usr/local/ nginx/ nginxCopy the code
LinuxThe installation
  • Linux install nginx
centOSThe installation
  • CentOS7 Installs nginx and nginx configuration

role

Forward agent
  • A location between the client and the original server (origin serverIn order to get content from the original server, the client sends a request to the agent and specifies the target (the original server). The agent then forwards the request to the original server and returns the obtained content to the client.

  • Features:
    1. The proxy server and the client are in the same LAN.
    2. The client specify the server address to access;
    3. The real client information is masked or hidden.
  • Function:
    1. Access previously inaccessible resources, such asGoogle;
    2. Can do cache, speed up access to resources;
    3. Client access authorization, Internet access authentication;
    4. The proxy can record user access records (online behavior management) and hide user information externally.
The reverse proxy
  • The way it works is that the proxy server accepts connection requests from the network. It forwards the request to the server on the internal network and returns the result from the server to the client requesting the connection on the network. At this time, the proxy server acts as a server externally.

  • Features:
    1. The proxy server and the source station are in the same LAN.
    2. The client has no perceptive proxy, and the reverse proxy is transparent to the outside world.
    3. Server information is hidden.
  • Function:
    1. To ensure Intranet security, the reverse proxy is usually used as the public network access address.WebThe server is an Intranet; ;
    2. Load balancing, using a reverse proxy server to optimize the load on your website.
Load balancing
  • Most are needed in high concurrency situations. Its principle is to spread the data traffic to multiple servers to perform, reduce the pressure of each server, multiple servers (cluster) to complete the work task, thus improving the data throughput.
  • Load balancing policies: Polling (default), Weighting (weight),ip_hash,url_hash(Third party),fair(Third party)
Dynamic and static separation
  • nginxThe static and dynamic separation is to separate the dynamic request from the static request, and the appropriate server processes the corresponding request, so that the performance and efficiency of the whole server system is higher.
  • nginxThe ability to forward different requests depending on the configuration is the basis for dynamic separation. Static resources corresponding to static requests can be placed directly onnginxBetter practice is to put on the corresponding buffer server. Dynamic requests are handled by the corresponding back-end server.
  • Basic code examples:
server { ... # all static request handled by nginx, storage directory location for HTML ~ \. (GIF | JPG | jpeg | PNG | BMP | | js SWF | CSS) ${root e: \ below; } # all dynamic requests are forwarded to tomcat to handle the location ~ \. | do (JSP) ${proxy_pass http://test; }}Copy the code

nginxConfiguration instructions

File structure

. # block events {# block events... } HTTP # HTTP block {... # HTTP global block server # server block {... Location [PATTERN] # location block {... } location [PATTERN] { ... } } server { ... }... # HTTP global block}Copy the code
  1. Global block: Configuration impactnginxGlobal instructions. Generally runningnginxThe user group of the server,nginxprocesspidSave path, log storage path, configuration file import, allow generationworker processNumber, etc.
  2. eventsBlock: Configuration impactnginxA server or network connection to a user. The maximum number of connections per process, which event-driven model to choose to handle connection requests, whether to allow simultaneous acceptance of multiple network connections, enable serialization of multiple network connections, etc.
  3. httpBlocks: You can nest more than oneserver, configure proxy, cache, log definition and most other functions and third-party module configuration. Such as file import,mime-typeDefine, log custom, whether to usesendfileTransfer files, connection timeout, number of single connection requests, etc.
  4. serverBlock: configures the parameters related to the virtual hosthttpThere can be more than oneserver.
  5. locationBlock: Configures the routing of requests and the processing of various pages.

Configuration file instance

########### Each instruction must end with a semicolon. ################# #user administrator administrators; Configure the user or group. Default is nobody nobody. #worker_processes 2; Pid /nginx/pid/nginx.pid Error_log log/error.log debug; Specify log path, level. This setting can fit into a global, HTTP, server block level to: debug | info | notice | warn | error | crit | alert | emerg events {accept_mutex on; Set network connection serialization to prevent stampedes, default to on multi_accept on; If a process accepts multiple network connections at the same time, the default is off. # event driven model, select | poll | kqueue | epoll | who | / dev/poll | eventport worker_connections 1024; HTTP {include mime.types; Default_type application/octet-stream; The default file type is text/plain #access_log off. Log_format myFormat '$remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; Access_log log/access.log myFormat; #combined = default value sendFile on; # allow sendFile transfer, default is off, HTTP block, server block, location block sendfile_max_chunk 100k; The number of transfers per call cannot exceed the set value. The default value is 0, that is, no upper limit is set. keepalive_timeout 65; # connection timeout, default is 75s, can be in HTTP, server, location block. Upstream mysvr {server 127.0.0.1:7878; 3333 backup server 192.168.10.121:; # hot standby} error_page 404 https://www.baidu.com; Server {keepalive_requests 120; # Maximum number of single connection requests. listen 4545; Server_name 127.0.0.1; Location ~*^.+${# request url filtering, regular matching, ~ is case sensitive, ~* is case insensitive. #root path; # root directory #index vv.txt; Proxy_pass http://mysvr; Mysvr defines the server list to deny 127.0.0.1; Allow 172.18.5.54; # allowed IP}}}Copy the code
  • Note:

    1. Each instruction must be terminated by a semicolon (after configuration is written, it can be usednginx -tCheck if it is correct).
    2. $remote_addr$http_x_forwarded_forTo record the clientipAddress;
    3. $remote_userUsed to record the client user name;
    4. $time_localUsed to record the access time and time zone;
    5. $requestThe URL and HTTP protocol used to record requests;
    6. $statusUsed to record request status (success is200);
    7. $body_bytes_s entRecord the size of the file body content sent to the client;
    8. $http_refererUsed to record visits from that page link;
    9. $http_user_agentRecord information about the client browser.
  • Stampede: when a network connection arrives, multiple sleeping processes are woken up at the same time, but only one process can get the connection, which affects system performance.

nginxCommon commands

help

nginx -h
Copy the code

Check the version

nginx -v
Copy the code

Check whether the configuration file is valid

nginx -t
Copy the code

View/Stop the process

Ps aux | grep nginx sudo kill 9 [below the process id (39349,...)"Copy the code

Start the

Nginx nginx - c/usr/local/etc/nginx/conf/nginx. Conf / / start the specified configuration fileCopy the code

restart

nginx -s reload
Copy the code

Stop the service

Nginx -s stop // violence stop nginx -s quit // graceful stopCopy the code

Refer to the link

  • Nginx has four functions
  • Nginx configuration details

Past wonderful

  • VS Code’s guide to improving development efficiency, quality, and coding experience
  • NPM and YARN Common operations guide
  • Gold nine front-end interview summary!
  • Build from 0 Vite + Vue3 + element-plus + VUE-Router + ESLint + husky + Lint-staged
  • “Front-end advanced” JavaScript handwriting methods/use tips self-check
  • Public account open small program best solution (Vue)
  • Axios you probably don’t know how to use

“Likes, favorites and comments”

❤️ follow + like + comment + share ❤️, lingering fragrance in hand, thank 🙏 everyone.