Nginx: static resource configuration instruction

Posted by paddycallaghan on Tue, 25 Jan 2022 15:14:18 +0100

listen instruction

listen: used to configure the listening port.

grammar listen address[:port] [default_server]...;
listen port [default_server]...;
Default value listen *:80 | *:8000
position server

The setting of listen is flexible:

listen 127.0.0.1:8000; // listen localhost:8000 listens to the specified IP and port
listen 127.0.0.1;	Listening assignment IP All ports of
listen 8000;	Listen for connections on the specified port
listen *:8000;	Listen for connections on the specified port

default_ The server property is an identifier used to set this virtual host as the default host. The so-called default host means that if the corresponding address:port is not matched, it will be executed by default. If not specified, the first server is used by default.

server{
	listen 8080 default_server;
	server_name localhost;
	default_type text/plain;
	return 444 'This is a error request';
}

server_name instruction

server_name: used to set the virtual host service name

127.0.0.1, localhost, domain name [www.baidu.com | www.jd.com]

grammar server_name name ...;
name can provide multiple, separated by spaces
Default value server_name "";
position server

About server_name can be configured in three ways:

  • Exact match
  • Wildcard matching
  • Regular Expression Matching

Exact match

    server {
        listen       80;
        server_name  www.wj4812.com;
        default_type text/plain;
        return 200 'hello';
    }
    server {
        listen       80;
        server_name  www.wj4811.com;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

Configure / etc/hosts:

127.0.0.1 www.wj4811.com
127.0.0.1 www.wj4812.com

Test:

Wildcard configuration

server_ The wildcard "*" is supported in name, but it should be noted that the wildcard cannot appear in the middle of the domain name, but only in the first or last paragraph, such as:

    server {
        listen       80;
        server_name  *.wj4812.com www.wj4812.*;
        default_type text/plain;
        return 200 'hello';
    }

The following configuration will report an error

    server {
        listen       80;
        server_name  www.*.com
        default_type text/plain;
        return 200 'hello';
    }

Regular expression configuration

server_ Regular expressions can be used in name, and ~ is used as the starting mark of the regular expression string.

Common regular expressions:

code explain
^ Match search string start position
$ Match search string end position
. Matches any single character except the newline character \ n
\ Escape character, marking the next character as a special character
[xyz] Character set that matches any specified character
[a-z] Character range that matches any character within the specified range
\w Match A-Z a-z 0-9 and underscore with any of the following characters, equivalent to [A-Za-z0-9_]
\d Numeric character matching, equivalent to [0-9]
{n} Exactly match n times
{n,} Match at least n times
{n,m} Match at least n times and at most m times
* Zero or more times, equivalent to {0,}
+ One or more times, equivalent to {1,}
? Zero or once, equivalent to {0,1}

The configuration is as follows:

server{
        listen 80;
        server_name ~^www\.(\w+)\.com$;
        default_type text/plain;
        return 200 $1  $2 ..;
}
#Note that ~ cannot be followed by spaces, and parentheses can take values

Match execution order

Due to server_ The name directive supports wildcards and regular expressions. Therefore, in a configuration file containing multiple virtual hosts, a server whose name is used by multiple virtual hosts may appear_ Name matching is successful. In this case, who will handle the current request?

server{
	listen 80;
	server_name ~^www\.\w+\.com$;
	default_type text/plain;
	return 200 'regex_success';
}

server{
	listen 80;
	server_name www.wj4811.*;
	default_type text/plain;
	return 200 'wildcard_after_success';
}

server{
	listen 80;
	server_name *.wj4811.com;
	default_type text/plain;
	return 200 'wildcard_before_success';
}

server{
	listen 80;
	server_name www.wj4811.com;
	default_type text/plain;
	return 200 'exact_success';
}

server{
	listen 80 default_server;
	server_name _;
	default_type text/plain;
	return 444 'default_server not found server';
}

Execution order: exact_ success ==> wildcard_ before_ success ==> wildcard_ after_ success ==> regex_ success ==> default_ server not found server

No1:Accurate matching server_name
No2:Wildcards match at the beginning server_name success
No3:Wildcards match at the end server_name success
No4:Regular Expression Matching  server_name success
No5:Default default_server Processing. If no default is specified, find the first one server

location instruction

location: used to set the URI of the request

grammar location [ = | ~ | ~* | ^~ |@ ] uri{...}
Default value
position server,location

The uri variable is the request string to be matched, which can contain neither regular expression nor regular expression. When searching for a matching location, the nginx server first uses the one that does not contain regular expression to find the one with the highest matching degree, and then matches through the one that contains regular expression. If it can be matched to direct access, If there is no match, the location with the highest matching degree just now is used to process the request.

Without symbol, it is required to start in the specified mode:

server {
	listen 80;
	server_name 127.0.0.1;
	location /abc{
		default_type text/plain;
		return 200 "access success";
	}
}
The following interviews are correct
http://192.168.200.133/abc
http://192.168.200.133/abc?p1=TOM
http://192.168.200.133/abc/
http://192.168.200.133/abcdef

=: must exactly match the specified pattern before using for URIs that do not contain regular expressions

server {
	listen 80;
	server_name 127.0.0.1;
	location =/abc{
		default_type text/plain;
		return 200 "access success";
	}
}
Can match to
http://192.168.200.133/abc
http://192.168.200.133/abc?p1=TOM
 Cannot match
http://192.168.200.133/abc/
http://192.168.200.133/abcdef

~: used to indicate that the current uri contains regular expressions and is case sensitive
~*: used to indicate that the current uri contains regular expressions and is not case sensitive

In other words, if the uri contains a regular expression, it needs to be identified by the above two matches

server {
	listen 80;
	server_name 127.0.0.1;
	location ~^/abc\w${
		default_type text/plain;
		return 200 "access success";
	}
}
server {
	listen 80;
	server_name 127.0.0.1;
	location ~*^/abc\w${
		default_type text/plain;
		return 200 "access success";
	}
}

^~: before being used for URIs that do not contain regular expressions, the functions are the same as those without symbols. The only difference is that if the patterns match, the search for other patterns will stop.

server {
	listen 80;
	server_name 127.0.0.1;
	location ^~/abc{
		default_type text/plain;
		return 200 "access success";
	}
}

Set the root and alias instructions of the directory requesting resources

Root: set the root directory of the request

grammar root path;
Default value root html;
position http,server,location

Path is the root directory path for the Nginx server to find resources after receiving the request.

alias: the URI used to change the location

grammar alias path;
Default value
position location

Path is the modified root path.

The above two instructions can specify the path to access resources. What is the difference between the two?

For example:

(1) Create an images directory in / usr/local/nginx/html directory and put an image MV in the directory Png picture

location /images {
	root /usr/local/nginx/html;
}

The path to access the picture is:

http://192.168.1.43/images/mv.png

(2) If you change root to alias

location /images {
	alias /usr/local/nginx/html;
}

If you visit the above address again, 404 error will appear on the page. If you check the error log, you will find that the address is wrong, so it is verified that:

root The result is: root route+location route
/usr/local/nginx/html/images/mv.png
alias The result is:use alias Path replacement location route
/usr/local/nginx/html/images

You need to change the path after alias to

location /images {
	alias /usr/local/nginx/html/images;
}

(3) If the location path ends with /, alias must also end with /, which is not required by root

Modify the above configuration to:

location /images/ {
	alias /usr/local/nginx/html/images;
}

Access will cause problems. Check the error log or the path is wrong, so you need to add alias after it/

Summary:

root The result is: root route+location route
alias The result is:use alias Path replacement location route
alias Is the definition of a directory alias, root Is the meaning of the top-level directory.
If location The path is/ending,be alias It must also be based on/ending, root No requirement

index instruction

index: set the default home page of the website

grammar index file ...;
Default value index index.html;
position http,server,location

index can be followed by multiple settings. If no specific access resources are specified during access, they will be searched in turn until the first one is found.

For example:

location / {
	root /usr/local/nginx/html;
	index index.html index.htm;
}
Access the location You can pass http://ip:port /, if nothing is added after the address, the default is to access index HTML and index Htm, find the first one to return

error_page instruction

error_page: set the error page of the website

grammar error_page code ... [=[response]] uri;
Default value
position http,server,location......

How to handle when the corresponding response code appears.

For example:

(1) You can specify a specific jump address

server {
	error_page 404 http://www.itcast.cn;
}

(2) You can specify a redirect address

server{
	error_page 404 /50x.html;
	error_page 500 502 503 504 /50x.html;
	location =/50x.html{
		root html;
	}
}

(3) Use the @ match of location to complete the display of error information

server{
	error_page 404 @jump_to_error;
	location @jump_to_error {
		default_type text/plain;
		return 404 'Not Found Page...';
	}
}

The optional option = [response] is used to change the corresponding code to another one

server{
	error_page 404 =200 /50x.html;
	location =/50x.html{
		root html;
	}
}
In this way, when the corresponding resource cannot be found in the return 404, you can see on the browser that the final returned status code is 200. Please pay attention to this and write it error_page For the following content, 404 needs to be followed by a space, and 200 cannot be preceded by a space

Static resource optimal allocation syntax

How to optimize the allocation of static resources by Nginx. Here you can optimize from three attribute configurations:

sendfile on;
tcp_nopush on;
tcp_nodeplay on;

(1) send "le" is used to enable efficient file transfer mode.

grammar sendfile on |off;
Default value sendfile off;
position http,server,location...

The process of requesting static resources: the client sends requests to the server through the network interface. The operating system transmits these client requests to the server-side application, and the server-side application will process these requests. After the request processing is completed, the operating system also needs to transfer the processing results back through the network adapter.

server {
	listen 80;
	server_name localhost;
	location / {
		root html;
		index index.html;
	}
}
stay html There is one in the directory welcome.html Page, access address
http://192.168.200.133/welcome.html

(2)tcp_nopush: this instruction will take effect only when sendfile is turned on. It is mainly used to improve the transmission 'efficiency' of network packets

grammar tcp_nopush on|off;
Default value tcp_nopush off;
position http,server,location

(3)tcp_nodelay: this instruction takes effect only when the keep alive connection is turned on to improve the 'real-time' of network packet transmission

grammar tcp_nodelay on|off;
Default value tcp_nodelay on;
position http,server,location

"Tcp_nopush" and "TCP"_ Nodelay "seems to be mutually exclusive, so why should we turn on both values? We need to know that the two values are compatible in versions after Linux 2.5.9. The advantage of turning on all three instructions is that sendfile can turn on an efficient file transfer mode, and tcp_nopush can ensure that the data packets are fully" filled "before being sent to the client, This greatly reduces network overhead and speeds up file sending. Then, when it reaches the last packet that may be suspended because it is not "full", Nginx ignores TCP_ Nopush parameter, and then TCP_ Nodelay forces the socket to send data. Therefore, TCP_ Nopush can work with TCP_ Set together with nodelay, which is better than configuring TCP separately_ Nodelay has stronger performance. Therefore, we can use the following configuration to optimize the processing of Nginx static resources

sendfile on;
tcp_nopush on;
tcp_nodelay on;

Topics: Nginx