nginx knowledge the front end must know

Keywords: Web Server Nginx axios VPN Javascript

The way forward for front-end developers has to learn nginx.

This article deals with

  • nginx command
  • Configuration file, configuration explanation
  • variable
  • Journal
  • Cross-domain
  • Proxy Request
  • location Interception Details
  • gzip
  • Anti-theft chain
  • Reverse Proxy, Forward Proxy
  • load balancing
  • cache
  • rewrite


  • Nginx-T View the current nginx final configuration
  • Nginx-t Check the configuration file for syntax errors
  • Nginx-s reload signals the main process to reload the configuration file
  • Nginx-s stop fast shutdown
  • Nginx-s quit Waits for worker process processing to complete before shutting down

configuration file

user  nginx; # Define users for Nginx to run
worker_processes  1; # Set the number of worker processes

error_log  /var/log/nginx/error.log warn; #nginx error log
pid        /var/run/; # stores the process number of nginx's master process

# Evets module contains settings for all processing connections in nginx
events {
    #Maximum number of connections to a worker process Theoretically the maximum number of connections per nginx server is worker_processes*worker_connections worker_processes the number of processes opened for us in the main
    worker_connections  1024;

# Provide some configuration parameters related to http services
http {
    # Incude is a main module directive that splits and references the configuration file to reduce the complexity of the main configuration file. Here are some file types to load
    include       /etc/nginx/mime.types;
    # default_type is an HTTP core module directive, where the default type is set to binary stream, which is used when the file type is undefined
    default_type  application/octet-stream;

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

    # Define the access log for this virtual host
    access_log  /var/log/nginx/access.log  main;
    sendfile on; #Turn on the efficient file transfer mode, the sendfile directive specifies whether nginx calls the sendfile function to output files. Set it to on for normal applications, off for heavy disk IO applications such as downloads, to balance disk and network I/O processing speed and reduce system load.Note: Change this to off if the picture does not display properly
    sendfile        on;
    tcp_nopush     on;

    keepalive_timeout  65;

    #gzip module settings
    gzip on; #Turn on gzip compressed output
    gzip_min_length 1k; #Minimum Compressed File Size
    gzip_buffers 4 16k; #Compression Buffer
    gzip_http_version 1.0; #Compressed version (default 1.1, use 1.0 for front end if squid2.5)
    gzip_comp_level 2; #Compression Level

    limit_zone crawler $binary_remote_addr 10m; #Use when opening a limit on the number of IP connections

    server {
        listen       80; # Represents the port on which http listens
        server_name  localhost; # Domains can have multiple names, separated by spaces, which can be distinguished by server_name when multiple servers are listening on the same port
        # Some directives can support regular expressions
        location / { # Used to match URI s, where you can also match regularly~to indicate case sensitive~*to indicate case insensitive
            root   html; # The root directory of the static file is specified
            index  index.html index.htm;
        error_page   500 502 503 504  /50x.html; # Indicates redirection to/50x.html when error code 500 502 503 504
        location = /50x.html {
            root   html;
    include /etc/nginx/conf.d/*.conf; # Used to load other profiles in


The value of the variable, $arg_PARAMETER, is the value of the variable name PARAMETER parameter in the GET request.

The variable $args is equal to the parameter in the GET request.For example, foo=123&bar=blahblah; this variable can only be modified

Client address in the form of binary_remote_addr binary code.

Bytes of $body_bytes_sent transfer page

The Content-length field in the $content_length request header.

The Content-Type field in the $content_type request header.

Value of $cookie_COOKIE cookie COOKIE.

$document_root currently requests the value specified in the root directive.

$document_uri is the same as $uri.

The host header (Host) field in the $host request, or the server name (the value of the server_name directive for the server that handles the request) if the host header in the request is unavailable or empty.The value is lowercase and does not contain ports.

$hostname machine name uses the value of the gethostname system call

The content in the $http_HEADER HTTP request header, HEADER lowercase for the content in the HTTP request, -becomes (dash becomes underscore), for example: $http_user_agent (value of Uaer-Agent), $http_referer...;

The contents in the $send_http_HEADER HTTP response header, HEADER lowercase the contents in the HTTP response, -change to (dash becomes underscore), for example: $send_http_cache_control, $send_http_content_type...;

$is_args If $args is set, the value is'?', otherwise it is'.

The variable $limit_rate limits the connection rate.

The version number of nginx currently running for $nginx_version.

$query_string is the same as $args.

IP address of the $remote_addr client.

Port for the $remote_port client.

The user name of $remote_user that has been authenticated by the Auth Basic Module.

The file path of the current connection request for $request_filename, generated by the root or alias directive and the URI request.

The variable $request_body (0.7.58+) contains the main information for the request.This makes sense in location s using the proxy_pass or fastcgi_pass directives.

Temporary filename of the $request_body_file client requesting principal information.

$request_completion is set to "OK" if the request succeeds; blank if the request is not completed or is not the last part of a series of requests.

The variable $request_method is the action requested by the client, usually GET or POST.
In versions including 0.8.20 and earlier, this variable is always an action in the main request and is not used if the current request is a child request.

The variable $request_uri is equal to the original URI that contains some client request parameters and cannot be modified. Please see if $uri changes or overrides the URI.

Protocols used by $scheme, such as http or https, such as rewrite ^(. +)$$scheme://$1 redirect;

The $server_addr server address, which can be determined after a system call is completed, must be specified in listen and the bind parameter used if you want to bypass the system call.

$server_name server name.

The port number on which the $server_port request arrives at the server.

The protocol used by $server_protocol requests is usually HTTP/1.0 or HTTP/1.1.



Indicates an error log.error_log /var/log/nginx/error.log warn;.The error log records information about access errors.Helps US troubleshoot errors.


Represents an access log.The log format log_format needs to be specified.By accessing the log, we can get the user's IP address, browser information, request processing time and so on.


The log format can be combined with the above variables to specify the output format for accessing the log.

For example:

log_format main '$host $document_uri $server_addr $remote_addr $remote_port';
server {
  listen 5002;
  access_log /usr/local/etc/nginx/servers/access.log main;
  location / {
    root /usr/local/etc/nginx/servers;
    index index.html;

Define a log format main

Then bind access_log to the log main


localhost /index.html 61517

As you can see, access_log is output in my main log format.


Believe you know CORS as a front-end developer.

  • Access-Control-Allow-Origin <origin> | *;

The value of the origin parameter specifies the foreign URI that allows access to the resource.For requests that do not require identity credentials, the server can specify that the value of this field is a wildcard character to allow requests from all domains.

  • Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header

When accessing across domains, the getResponseHeader() method of the XMLHttpRequest object only gets some of the most basic response headers, Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma, and if you want to access other headers, the server needs to set this response header.

  • Access-Control-Max-Age

The Access-Control-Max-Age header specifies how long the results of a preflight request can be cached; Access-Control-Max-Age: 86400

  • Access-Control-Allow-Credentials

Specifies whether the browser is allowed to read the contents of the response when its credentials are set to true.When used in response to a preflight pre-detect request, it specifies whether credentials can be used for the actual request.Note: Simple GET requests are not previewed; if the field is not included in the response to such requests, the response will be ignored and the browser will not return the content to the Web page

Not much, just paste the code below:

// index.js
import axios from 'axios'

axios.get('').then(res => {
    console.log(res, 'res')
server {
    listen 5556;
    location /api {
        proxy_pass http://localhost:5000;
        add_header Access-Control-Allow-Origin *;

Forward the request path/api start of port 5556 to the node service on port 5000.Add Access-Control-Allow-Origin * to solve cross-domain problems.

Proxy Request

A proxy request can see the cross-domain above.Forward requests from port 5556 to services on port 5000.

location Interception Details


  • =: Exact match path
  • ~: Indicates that the path is matched regularly after the symbol, case sensitive
  • ~*: Indicates that the path is matched regularly after the symbol, case-insensitive
  • ^~: Indicates that if the character following the symbol is the best match, the rule is applied and subsequent lookups are not performed.
location = / {
    [ configuration A ]

location / {
    [ configuration B ]

location /api/ {
    [ configuration C ]

location ^~ /static/ {
    [ configuration D ]

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]

Request/Precision Match A, no longer look down.

Request/index.html matches B.Find the matching prefix character first, find the longest match is Configuration B, and then find the matching regular in order.The result was not found, so the longest match with the previous tag, Configuration B, was used.

Request/api/list matches C.The longest matching C is found first, and since there is no regular matching behind it, the longest matching C is used.

Request/user/1.jpg matches E.The prefix character search is performed first, the longest match C is found, the regular search continues, and the match E is found.So use E.

Request/static/img.jpg matches D.The prefix character is first searched to find the longest matching D.However, the special feature is that it uses the ^~modifier and no more regular matching lookups follow, so it uses D.Here, if there is no previous modifier, the final match is actually E.

Request/router/pageA matches B.Because B means that any URL s starting with/match.In the configuration above, only B can satisfy, so match B.


Configuration Instructions

# Gzip Default off Default off gzip
gzip             on;
# gzip_min_length default 0
# Scope: http, server, location
# Sets the minimum number of bytes of pages that are allowed to compress, which is obtained from Content-Length in the header header.
# The default value is 0, regardless of how many pages are compressed.
# It is recommended to set the number of bytes to be greater than 1k, less than 1K may increase the pressure.That is: gzip_min_length 1024
gzip_min_length  1k;
# gzip_comp_level default 1 range 1 ~ 9
# Scope: http, server, location
# gzip compression ratio, 1 compression is the fastest than the minimum processing speed, 9 compression is the largest but processing is the slowest (transmission is fast but consumes cpu).
gzip_comp_level  6;
# Default value: gzip_types text/html
# Scope: http, server, location
# Matching MIME types for compression (whether specified or not) will always compress the "text/html" type.
# Note: If used as an http server, the main profile will contain a file type profile
gzip_types       text/plain application/x-javascript text/css application/xml application/javascript application/json;

Code demonstration

server {
  listen 9002;
  #gzip on;
  location / {
    root /usr/local/etc/nginx/servers/;
    index gzip.html;

Let's first record the file size that was loaded when gzip was not opened

size shows 1.3kb

Then we remove the gzip comment as follows

You can see that there are only 300B, but you can also control the size of the output according to other configurations, such as controlling the compression level.We can turn on gzip when packaging our front-end projects so that nginx does not have to compress gzip on the server.

Anti-theft chain

location ~ .*\.(jpg|png|gif)$ {
  valid_referers none blocked;
  if ($invalid_referer) {
    return 403;
  root /data/images;

valid_referers none | blocked | server_names | string ....;
none detects requests that do not exist in the Referer header domain
blocked detects when the Referer header field value is deleted or masqueraded by a firewall or proxy server.
In this case, the value of the header field is not "http:// "Or start with"https://"
server_names sets one or more URLs to detect if the value of the Referer header field is one of those URLs.
The use of the wildcard character'*'has been supported since nginx 0.5.33.

valid_referers are used to support referers accessing this resource

The variable $invalid_referer is true to indicate that it does not conform to the rules defined above.On return 403

Reverse Proxy, Forward Proxy

Forward Proxy

location / {
  proxy_pass http://$http_host$request_uri;

Forward proxy can be understood as a proxy client, such as a VPN.Because domestic websites cannot be accessed from abroad, VPN forwards your requests to the VPN server, which forwards your requests to the foreign websites unchanged.Forward proxy, the client knows the server, the server does not know the client.

Reverse Proxy

For example, load balancing will be discussed below.All requests go to a single nginx service, which tells you that requests are assigned to multiple servers.

load balancing

Code demonstration

├── 9004.html
├── 9005.html
├── 9006.html
└── upstream.conf
server {
    listen 9004;
    location / {
        root /usr/local/etc/nginx/servers/;
        index 9004.html;
server {
        listen 9005;
        location / {
                root /usr/local/etc/nginx/servers/;
                index 9005.html;
server {
        listen 9006;
        location / {
                root /usr/local/etc/nginx/servers/;
                index 9006.html;
upstream atie {
    server localhost:9004;
    server localhost:9005;
    server localhost:9006;

server {
    listen 9003;
    location / {
        proxy_pass http://atie;


From the code above, I can see that I can balance to other ports by accessing port 9003.

Open your browser and visit localhost:9003 to see that the pages will load 9004 ~ 9006.html pages, respectively

Introduction to configuration

state describe
down Not participating in load balancing
backup Backup Server
max_fails Number of Allow Request Failures
fail_timeout Time the service was paused after max_fails failed
max_conns Limit maximum number of connections received
weight Weight Ratio
upstream atie {
    server localhost:9004 down; # If down is added here to indicate load balancing, it will not go to this service
    server localhost:9005 backup; # Indicates that a backup will not go to this backup service until the service hangs up
    server localhost:9006 max_fails=1 fail_timeout=10s; # After the maximum number of times, new requests will not be assigned to this machine within the fail_timeout time.
upstream atie {
    server localhost:9004 weight=1;
    server localhost:9005 weight=2;
    server localhost:9006 weight=3;

When you visit 6 times, walk to 9004 2 times to 9005 3 times to 9006


Set expiration time by adding cache request header, etc.

location ~ .*\.(gif|jpg|png|css|js)(.*) {
    expires 90d; # Set valid 90 days


The rewrite function is to rewrite and redirect URLs using global variables provided by nginx or variables set by itself, combined with regular expressions and flags.Rewrites can only be placed in server{},location{},if {}, and can only work on strings behind domain names other than passed parameters

location / {
    rewrite /rewrite/(.*) http://www.$;
    return 200 "ok";
# Enter in the browser
# Temporarily redirect to
# Later return instructions will have no opportunity to execute

Posted by gmwebs on Sat, 31 Aug 2019 10:14:42 -0700