preface

Nginx as a Web server with low memory, high scalability, and easy to support 1-3W stand-alone concurrent links (said to support 10W stand-alone, but not see the specific machine configuration) is widely favored by developers.

It is recommended to use Nginx on Linux systems, which take full advantage of Linux features and provide better performance than on Windows.

Main contents of this paper:

  • Nginx simple configuration
  • Difference between root and alias
  • Location priority and validation
  • Nginx built-in variables
  • if
  • Rewrite the forwarding
  • try_files
  • Configuring gzip
  • Introduction and configuration of negotiated caching and strong caching

In the following sections, I will use AB pressure test to optimize the configuration of Nginx step by step. Nginx knows the principle and knows the common configuration. There are performance optimizations that require knowledge of the Linux kernel, HTTP, and TCP. If you don’t want to know, you can write down your own configuration and don’t worry about why.

Nginx 1.16.1, Centos 7, 4 cores, 8 GB memory VIRTUAL machine.

Nginx installation

Nginx installation steps

Configure yum source according to Ali CentOS image to improve download speed.

Ali epel mirror configuration of our common software package, Nginx is also among them.

# Run the command to update the yum source
yum clean all
yum makecache
Copy the code

After refreshing the YUM repository information, run the following command to find nginx

yum list | grep nginx
Copy the code

Install nginx

sudo yum install nginx
Copy the code

Configure nginx startup

sudo systemctl enable nginx
Copy the code

Start the nginx

sudo systemctl start nginx
Copy the code

Check whether nginx is started

sudo systemctl status nginx
Copy the code

If you want to see which files are installed in the nginx package, you can use the

rpm -qvl nginx
Copy the code

Nginx command

# Force immediate shutdown, not recommended
nginx -s stop

# closed normally, it will process incoming requests, but will not accept new requests
nginx -s quit

Reload the configuration file
nginx -s reload

# Reopen the log file
nginx -s reopen

Check the configuration file for errors
nginx -t

# Check whether the configuration file is incorrect. The configuration file will be printed
nginx -T

# Check the nginx version
nginx -v

# View nginx version and compile configuration disabled
nginx -V
Copy the code

The system starts, closes, restarts, and views the nginx command

sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl restart nginx
sudo systemctl stop nginx
sudo systemctl status nginx
Copy the code

Nginx simple configuration

Nginx is introduced

Deployed Nginx uses a master process to manage multiple worker processes. The master process does not process requests, but provides management services, including starting, stopping, reloading configuration files and other services. It is usually started as the root user. The worker process handles requests and is generally enabled with a non-administrator account. Reduce CPU switching caused by process switching.

Configuration in the HTTP context is the most important thing we need to know, and the rest will be configured.

The Server configuration

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    server {
        listen 80 ;
        server_name _;
        root /usr/share/nginx/html;
        location/ {}}}Copy the code

The Server is configured with a service.

Listen 80 is used to configure the listening service on port 80.

Root Specifies the location where static resources are stored.

Location Matches resources. Location / {} matches all resources.

listenserver_nameconfiguration

Matching rules:

  • Match the firstlistenMatch againserver_name
  • server_nameMatches in the request headerHost
  • If no match is found, the configuration is performeddefault_serverThe processing of
  • None of the above matches are successful and the first configuration handles this
server {
    listen 9099 default_server;
    server_name "localhost";

    location / {
        return 200 "Server_name for localhost"; }}server {
    listen 9099;
    server_name 127.0.0.1;

    location / {
    	return 200 "Server_name for 127.0.0.1"; }}server {
    listen 9099;
    server_name "localhost77";

    location / {
    	return 200 "Server_name for localhost77"; }}Copy the code

Set the request header Host in Postman to simulate access.

http://localhost:9099 Host:127.0.0.1 Returns server_name as 127.0.0.1

http://localhost:9099 Host:localhost Returns server_name as localhost

http://localhost:9099 Host: localHost77 The server_name is localhost77

http://localhost:9099 Host:localhost779 Return server_name as localhost

Add one more configuration

server {
    listen localhost:9099 default_server;
    server_name "localhost";

    location / {
        return 200 "Server_name is localhost: 9099"; }}Copy the code

When listen calls localhost:9099, server_name is returned as localhost:9099, because this is the only match.

If you want to disallow access without a Host header.

server {
    listen      80;
    server_name "";
    # indicates that nginx closes the connection
    return 444; 
}
Copy the code

returnconfiguration

Return defines the status code or content to return.

Return is introduced to describe location configuration

instructions
grammar return code [text];

return code URL;

return URL ;
The default
context Server, location, if

Code indicates the status code. Text is a string.

location /a {
    default_type application/json;
    return 200 "Access to 9088 / a";
}
Copy the code
# redirect
location = /b {
    return 301 http://www.baidu.com;
}
Copy the code

locationconfiguration

Location is used to match resources.

A smaller number indicates a higher priority.

Rules of the symbol describe priority
location = /a{} It’s a perfect match. When it’s done 1
location ^ ~ /a{} The prefix matches, and when it matches 2
location ~ /a.*{} Regular match, case sensitive, after checking, will also check whether there is a priority with higher 3
location ~* /a.* Re – match, case – insensitive, check after, will also check whether there is a priority with higher 4
location /a {} Also represents a prefix match, but has a lower priority than a regular match./a^~/aWill conflict, error reported 5
location / {} Anything that doesn’t match will be matched and processed here 6
server {
        listen 9088 default_server;
        server_name_;location = /a {
            default_type application/json;
            return 200 "= /a, first priority";
        }
        location^ ~ /a {
            default_type application/json;
            return 200 "^~ /a matches paths starting with /a, with second priority";
        }

        location ~ /a\.* {
            default_type application/json;
            return 200 "/a\.* match /a... Path, priority three.";
        }
        location ~* /a\.* {
            default_type application/json;
            return 200 "~* /a\. Path, priority four.";
        }
    	# /a will conflict with ^~ /a
        location /a/ {
            default_type application/json;
            return 200 "Matching/a/a / /... Path, priority five."; }}Copy the code

To verify this rule, visit http://localhost:9088/a and comment the higher-priority ones in turn.

There is also a special type of location that configures jumps, starting with @

location @pass{}Copy the code

Add_header adds the response header

instructions
grammar add_header name value [always];
The default
context HTTP, server, location, if in location

If the response code equals 200, 201, 204, 206, 301, 302, 303, 304, 307, or 308, the specified field is added to the response header.

Always always regardless of the status code.

location ~ /a\.* {
    default_type application/json;
    add_header test1 "asdfasdf" always;
    return 200 "/a\.* match /a... Path, priority three.";
}
Copy the code

error_page

instructions
grammar Error_page code... [=[response code]] uri;
The default
context HTTP, server, location, if in location

The page for redirecting the configuration error status code is displayed.

error_page 404 /404.html; 
error_page 500 502 503 504 /50x.html;
Copy the code

The above does not change the response status code.

# change the response status.
error_page 404 =200 /404.html;
Copy the code
server {
    location / {
       error_page 404 =  @ops-coffee;
    }

    location @ops-coffee {
       rewrite. * /permanent; }}Copy the code

Difference between root and alias

Alias is a path replacement. Location ends with a slash. Alias must end with a slash. Strict match. Alias Replaces the location path.

# /bieming/     替换  /usr/local/var/www/alias2/
# visit/bieming / 1. JPG to find/usr/local/var/WWW/alias2/1. JPG
location /bieming/ {
    alias /usr/local/var/www/alias2/;
}
Copy the code

Root indicates the root path plus + location path. Will compress two or more/into one.

When location and the last part of the root path match, it is better to use root
The following configurations can be used.
# visit/data2/1. JPG to find/usr/local/var/WWW/data2/1. JPG
location /data2/ {
    root /usr/local/var/www;
}
location /data2/ {
    root /usr/local/var/www/;
}
location /data2 {
    root /usr/local/var/www;
}
location /data2 {
    root /usr/local/var/www/;
}
location /data2/ {
    root /usr/local/var/www////;
}
Copy the code

Built-in variables

With built-in variables, we can forward or deny access by determining headers and Query String equivalents.

$arg_nameGet request parameters

Gets the name parameter in the request Query String.

location /arg/ {
    default_type application/json;
    return 200 "$arg_q1";
}
Copy the code

/arg/a? Q1 =334 returns 334.

$argsGet requestquery_stringparameter

location /arg/ {
    default_type application/json;
    return 200 "$arg_q1 _ $args";
}
Copy the code

Browser access /arg/a? Q1 =3334&aa=2&bb=33 Returns 3334_ Q1 =3334&aa=2&bb=33

$cookie_nameGets the value of the cookie

Gets the cookie named name in the request.

$http_nameGet the request header

Name is the field name in the request header, all lowercase, and replace the dash – with the underscore _

$http_user_agent gets the User-agent field in the request header.

$uriIn the request pathpath

Path is the path behind the port, excluding the Query String. Optimized path, special character translation and/compression.

The path to/arg/a http://localhost:8888/arg/a?q1=q1canshu&bb=2323

$hostFetch requestedip

The first thing we get is a request header Host, or if there’s no Host in the request header, then we get the IP in the URL.

$request_uriTo obtainpathquery string

Go to http://localhost:8888/arg/a/? q1=q1canshu&bb=2323

$request_uri/arg/a/?q1=q1canshu&bb=2323

$schemeAccess request protocol

The value can be HTTP or HTTPS

$request_methodGet request method

Obtain values in all uppercase letters. The GET, POST, DELETE, PUT, etc

Other variables

describe
$content_length To obtainContent-LengthRequest header field.
$content_type To obtainContent-TypeRequest header field
$https On if the connection is running in SSL mode, otherwise empty string
$is_args If the request line has arguments? Otherwise, an empty string
$pid Gets the object that processes the current requestworker pid
$nginx_version Get the version of nginx

if

instructions
grammar if (condition) {}
The default
context Server, the location,

After the specified condition is evaluated, if true, the module’s instructions specified in braces are executed and the request is assigned configuration within the if directive. The configuration within the if directive inherits from the configuration level of the previous layer.

Condition can be any of the following:

  • Variable name, false if the value of the variable is an empty string or 0

  • Use = and! The = operator compares variables and strings

  • Using the ~ (case-sensitive matching) and ~* (case-insensitive matching) operators, variables are matched against regular expressions. Regular expressions can be included for later use in $1.. Capture of reuse in the $9 variable.

  • Antioperator! ~ and! ~* is also available. If the regular expression contains} or; Character, the entire expression should be enclosed in single or double quotation marks.

  • Use -f and! The -f operator checks whether a file exists

  • Use -d and! The -d operator checks whether the directory exists

  • Use -e and! The -e operator checks whether a file, directory, or symbolic link exists

  • Use -x and! The -x operator checks for an executable

A space is required between the if and the parenthesis

location = /a {
    default_type application/json;
    if ($request_uri ~* "/(a).*") {
        return 200 "The value captured by the regular expression:The $1";
    }
    return 200 "= /a, first priority";
}
Copy the code

rewrite

instructions
grammar rewrite regex replacement [flag];
The default
context Server, location, if

Flag Optional parameters:

  • last

Stop the match and send a new request to match the location.

  • break

Stop matching and search for resources in the current location.

  • redirect

Temporary redirect. Return status code 302.

  • permanent

Permanent redirect. Return status code 301.

The specified regex matches, and the URI is handled according to replacement.

Verify break and last

The following three images all exist, but the content is different.

/Users/zhangpanqin/stduy_app/break2/test/1.jpg

/Users/zhangpanqin/stduy_app/last2/test/1.jpg

/Users/zhangpanqin/stduy_app/test/1.jpg

location /break2 {
    root /Users/zhangpanqin/stduy_app/break2;
    rewrite /break2/(.*) /test/The $1 break;
}

location /last2 {
    root /Users/zhangpanqin/stduy_app/last2;
    rewrite /last2/(.*) /test/The $1 last;
}

location /test/ {
    root /Users/zhangpanqin/stduy_app;
}
Copy the code

When accessing /break2/1.jpg actually matches the first location, it is then processed in the current context.

/break2/1.jpg is replaced with /test/1.jpg, and then combined with the path specified by root, returns /Users/zhangpanqin/stduy_app/break2/test/1.jpg data.

When /last2/1.jpg is accessed, the URI is replaced with /test/1.jpg to match the new location for processing.

The contents of /Users/zhangpanqin/stduy_app/test/1.jpg are returned.

validationredirectpermanent

location /redirect2 {
    rewrite ^/redirect2 http://www.baidu.com redirect;
}

location /permanent2 {
    rewrite ^/permanent2 http://www.baidu.com permanent;
}
Copy the code

After both matches are successful, the browser address bar is changed. The browser jumps to the corresponding address based on the Location header.

The difference is that a permanent redirect (permanent), the browser will keep records, when to visit http://localhost:9088/permanent2 and do not ask nginx jump directly.

For temporary redirects, the browser asks Nginx where it needs to jump to each time. You can turn off nginx to see the validation results.

try_files

instructions
grammar try_files The file... uri;

try_files The file... =code;
The default
context Server, the location,

Checks for the existence of files in the specified order and uses the first file found for request processing. If the content cannot be found, it is forwarded internally to the last parameter URI. The file location is root + file.

location /try/ {
    root /usr/local/var/www/data2/data2/;
    try_files $uri $uri/ @pass2;
}
location @pass2 {
    default_type application/json ;
    return 200 "No data to page broker" ;
}
Copy the code

When /try/1.jpg is accessed, $uri is /try/1.jpg.

Root + $uri of/usr/local/var/WWW/data2 / data2 / try / 1. JPG find back, continue to match back not found. None of them matched internal forwarding to @pass2.

If you want to verify jumps like /try/test, do not use suffix names, because the browser will return the content-Type, causing the content to be inconsistent with the parse, and the image will not be displayed.

Configuring gzip

# open gzip
gzip on;

# add to the response header, Vary: accept-encoding
gzip_vary on;

# gzip compression level 1-9, the larger the number, the better the compression effect, the longer the compression time, the higher the CPU usage
gzip_comp_level 6;

If the size of the source file exceeds 8K, the size of the source file is 16*8K.
gzip_buffers 16 8k;

gzip_min_length 2K;
gzip_proxied any;
gzip_disable "msie6";

gzip_http_version 1.1;

# Text (JS, text, CSS, XML, JSON) compression is better, images have been compressed, the effect is not very obvious, but also a waste of CPU
gzip_types text/plain text/css text/xml text/javascript application/javascript application/json application/xml+rss application/rss+xml application/atom+xml image/svg+xml;

Copy the code

Gzip compression works best for text, and is recommended for text compression only.

Configure the cache

To reduce server stress and save bandwidth, you can configure caching.

Memory cache: It is used to cache resource files into memory. The cache is loaded directly from memory.

Disk cache: It is used to cache resource files to the hard disk. The cache is loaded directly from the hard disk.

If no network resource is found in the disk cache, request network resources.

Caches are classified into negotiation cache and strong cache.

The negotiated cache will go to the server every time to ask if the cache has expired. If it has not expired, the local cache will be used.

A strong cache has a cache expiration period, during which the server does not check the cache and uses the local cache directly.

Webpack can now produce files like app.asdfa21342.js based on the hash of the file’s contents. When a website is updated, new pages will parse and load different resources, thus reducing the performance of the server caused by cache verification.

Negotiate the cache

Negotiation caches include ETag/ if-none-match and last-modified/if-modify-since.

The HTTP protocol states that when both types of response headers exist, they must be met before caching can be used.

ETag/if-None-Match

instructions
grammar etag on|off;
The default etag on;
context HTTP, Server, location

Nginx has an eTAG configuration attribute that generates an ETAG response header with a hash value for the file content for each static resource.

When the browser accesses the resource for the first time, it returns a response with an Etag in the header.

Nginx returns a request header if-none-match with the value of Etag to check whether the cache is the same. If the request header is Etag, the cache is not expired, and 304 status code is returned. If the request header is not Etag, nginx returns a request header if-none-match with the value of Etag. Return status code 200.

Last-Modified/if-Modify-Since

instructions
grammar if_modified_since off|exact|before;
The default If_modified_since exact;
context HTTP, Server, location

Specifies how to compare the file modification time with the request header if-modified-since:

  • off

Ignore if-Modified-since request header field (0.7.34)

  • exact

An exact match

  • before

The resource’s modification time is less than or equal to the time in the if-Modified-since request header field

When the browser accesses a resource for the first time, the last-Modified response header is returned, indicating when the file was Last Modified.

When the browser accesses the same resource again as normal (without forcing a refresh of the resource), the request header is appended with if-modified-since, which is the last-modified value previously returned. If-modified_since nginx receives if-modified-since and compares the last-modified time of the resource with the if-modified_since attribute. If the match is successful, the cache is hit. Return 304, otherwise return the resource with status code 200, and update the cache time.

Mandatory cache

Expires

Expires is the HTTP1.0 specification, and its value is an absolute time GMT-formatted time string. This time represents the expiration time of the resource. If requested before this time, it will be read from the cache. If the time zones of the server and client are different, the judgment may be inaccurate.

Cache-Control

Cache-control is the HTTP1.1 specification, which uses the max-age value of this field to determine. The value is a relative time. For example, cache-control: max-age=3600 indicates that the validity period of the resource is 3600 seconds. In addition to this field, we have the following fields to set:

No-cache: negotiates the cache and sends a request to the server to confirm whether the cache is used.

**no-store: ** Disallows the use of caching, and rerequests data each time.

**public: ** can be cached by all users, including end users and intermediate proxy servers such as CDN.

**private: ** can only be cached by the end user’s browser, not by CDN and other trunk cache servers.

Configure the cache

location ~* \.(css|js|png|jpg|jpeg|gif|gz|svg|mp4|mp3|ogg|ogv|webm|htc|xml|woff)$ {
    Turn off access logging
    access_log off;
    # Strong cache, for one year, browser and CDN middleware can cache
    add_header Cache-Control "max-age=31536000";
}
Copy the code

Recommended data

Nginx 中文 版