I. HTTP server
Nginx itself is also a server with static resources. When there are only static resources, Nginx can be used as a server. If a website is only static pages, then it can be deployed in this way.
/usr/local/var/ WWW/test.html; /usr/local/var/ WWW/test.html;
2. Configure server in nginx.conf
user mengday staff; http { server { listen 80; server_name localhost; client_max_body_size 1024M; # default location location / {root /usr/local/var/ WWW/HTML; index index.html index.htm; }}}Copy the code
3. Access testing
http://localhost/
Point to the/usr/local/var/www/index.html
, index.html is the HTML that comes with installing nginxhttp://localhost/test.html
Point to the/usr/local/var/www/html/test.html
Note: If the error 403 Forbidden is displayed when accessing images, it may be because the user configuration in the first line of nginx.conf is incorrect. The default is #user nobody. It’s a comment. On Linux, it’s user root; For macOS, change the group to user. Then reload the configuration file or restart and try again. The user name can be viewed using the who am I command.
4. Introduction to instructions
- Server: Used to define a service. HTTP can have multiple server blocks
- Listen: Specifies the IP address and port on which the server listens for requests. If the address is omitted, the server listens for all addresses. If the port is omitted, the standard port is used
- Server_name: indicates the service name, which is used to configure the domain name
- location : A server can have multiple locations. The location can be followed by a URI, which can be a regular expression. / indicates that any path is matched
- Root: indicates the root path
http://localhost/test.html
, “/test. HTML” will match the “/” URI, find root is/usr/local/var/www/html
, the physical address of the resource that the user accesses =root + uri = /usr/local/var/www/html + /test.html=/usr/local/var/www/html/test.html
- Index: sets the home page, when only access
server_name
If you do not follow any path, you can directly follow the index command instead of the root command. If no specific file is specified in the access path, the resource set by index is returnedhttp://localhost/html/
By default, index.html is returned
5. Location URI regular expression
.
: Matches any character except the newline?
: Repeat 0 times or 1 time+
: Repeat 1 or more times*
: Repeat 0 or more times\d
: Match number^
: Matches the beginning of the string$
: Matches the end of the string{n}
: repeat n times{n,}
: repeat n or more times[c]
: matches a single character c[a-z]
: Matches any lowercase letter a to Z(a|b|c)
: Indicates that any cases are matched. Each case is separated by a vertical line and usually enclosed by curly brackets. The matches match the strings that match a, B, or C characters\
Backslash: Used to escape special characters
Anything that matches between parentheses () can be referred to later by $1, with $2 referring to the second () above. What can get confusing in re is the \ escape special character.
Two, static server
Static servers are often encountered in companies, often providing an upload capability from which other applications can obtain static resources if they need them.
Create images and img directories in /usr/local/var/www and place test.jpg in each directory
http { server { listen 80; server_name localhost; set $doc_root /usr/local/var/www; # default location location / {root /usr/local/var/ WWW/HTML; index index.html index.htm; } location ^~ /images/ { root $doc_root; } location ~* \.(gif|jpg|jpeg|png|bmp|ico|swf|css|js)$ { root $doc_root/img; }}}Copy the code
Custom variables use the set instruction, syntax set variable name value; References use the variable name value; References use variable names; The doc_root variable is custom here.
There are two ways to map a static server location:
- Use a path, such as /images/, where images are usually stored in an image directory,
- Use suffixes such as.jpg and.png to match patterns
http://localhost/test.jpg will be mapped to $doc_root/img
Visit http://localhost/images/test.jpg when the same path to satisfy multiple location, give priority to match the location of the highest priority, because of greater than ~ ^ ~ priority, so will walk/images/corresponds to the location
Common location path mapping paths are as follows:
=
Perform an exact matching of ordinary characters. It’s a perfect match.^ ~
Prefix matching. If the match is successful, no other location is matched.~
Indicates that a regular match is performed, case sensitive~ *
Indicates that a regular match is performed, case insensitive/xxx/
Regular string path match/
Generic match, any request will match
The location priority
When a path matches multiple locations, there is a priority order for which location matches. The priority order depends on the expression type of the location value, and is independent of the order in the configuration file. For expressions of the same type, the length of the string matches first. Recommended: Java interview questions
Here are the instructions in order of priority:
- The equals type (=) has the highest priority. Once a match is found, the search stops.
^ ~
Type expressions are not regular expressions. Once a match is found, the search stops.- Regular expression types (
~ ~ *
) has the highest priority. If multiple locations match the regular expression, the one with the longest regular expression is used. - Regular string match type. Matches by prefix.
- / generic. If none is found, generic is matched
Priority search problem: Different types of location mapping determine whether to continue searching down
- Equal sign type,
^ ~
Type: Once a match is found, the search stops. No other location will be matched - Regular expression types (
~ ~ *
), the general string match type/xxx/
: After a match is found, the search will continue for other locations until the highest priority is found, or the search will stop when the first case is found
Location priority from top to bottom:
(location =) > (location ^~ path) > (location ^~ path) > (location ~,~* regular order) > (location partial start path) > (/)
[configuration A]} location / {# matches all requests that start with /. # But if there is a longer expression of the same type, select the longer expression. If there is a regular expression to match, match the regular expression first. [configuration B]} location /documents/ {# match all requests starting with /documents/. # But if there is a longer expression of the same type, select the longer expression. If there is a regular expression to match, match the regular expression first. [configuration C]} location ^~ /images/ {# Match all expressions starting with /images/. # so, even if there were in line with the regular expression location, also won't be used [configuration D]} \. The location ~ * (GIF | JPG | jpeg) ${# matches all ends in GIF JPG jpeg's request. [Configuration E]} location /images/ {# match to /images/, [configuration F]} location = /test.htm {root /usr/local/var/www/htm; index index.htm; }Copy the code
Note: The priority of location is independent of the location configured for location
Three, reverse proxy
Reverse Proxy is the most commonly used function in Nginx. Reverse Proxy means that a Proxy server accepts connection requests from the Internet, then forwards the requests to the server on the internal network, and returns the results obtained from the server to the client requesting connection on the Internet. In this case, the proxy server behaves as a reverse proxy server.
In short, the real server cannot be directly accessed by the external network, so a proxy server is required. The proxy server can be accessed by the external network, but it is in the same network environment as the real server. Of course, the proxy server may also be the same server with different ports.
The reverse proxy is implemented through the proxy_pass directive.
Start a Java Web project at port 8081
server { listen 80; server_name localhost; location / { proxy_pass http://localhost:8081; proxy_set_header Host $host:$server_port; Proxy_set_header x-forwarded-for $remote_addr; Proxy_next_upstream error timeout invalid_header http_500 HTTP_502 HTTP_503; }}Copy the code
When we access localhost, we’re accessing localhost:8081
Iv. Load balancing
Load balancing is also a common function of Nginx. Load balancing means that it is distributed among multiple operation units, such as Web servers, FTP servers, enterprise critical application servers, and other mission-critical servers, so that work tasks can be completed together.
In simple terms, when there are two or more servers, the requests are randomly distributed to the specified server for processing according to the rules. In load balancing configuration, the reverse proxy needs to be configured at the same time to jump to the load balancing through the reverse proxy. Nginx currently supports three load balancing policies and two commonly used third-party policies.
Load balancing is done through the upstream directive.
1. RR(round robin: default)
Each request one by one in chronological order allocation to different backend server, that is to say, on the first request assigned to the first server, the second request assigned to the second server, if there are only two servers, the third request assigned to the first stage, cyclic polling like this, and also is the server receives the request ratio is 1:1, If the back-end server is down, it is automatically deleted. Polling is the default configuration and does not require much configuration
The same project starts the project using ports 8081 and 8082, respectively
upstream web_servers { server localhost:8081; server localhost:8082; } server { listen 80; server_name localhost; #access_log logs/host.access.log main; location / { proxy_pass http://web_servers; Proxy_set_header Host $Host :$server_port; }}Copy the code
Visit http://localhost/api/user/login? address can still get the response Username =zhangsan&password=111111, this method is polling
2. The weight
When you specify the polling probability, the weight is proportional to the access ratio, that is, the proportion of requests received by the server is the proportion of the configured weight, which is used in the case of uneven backend server performance. For example, if the server performance is poor, it will receive fewer requests, and if the server performance is good, it will process more requests.
upstream test {
server localhost:8081 weight=1;
server localhost:8082 weight=3;
server localhost:8083 weight=4 backup;
}
Copy the code
The example is that only one of the four requests is allocated to 8081, and the other three are allocated to 8082. Backup indicates hot backup. You can run 8083 only when both 8081 and 8082 are down
3. ip_hash
The problem with both methods is that the next request may be sent to another server. When our application is not stateless (using session to store data), there is a big problem, such as saving login information to the session. In many cases, we need a client to access only one server, so we need to use iphash. Each request of iphash is assigned according to the hash result of the access IP, so that each visitor accesses a fixed back-end server, which can solve the session problem.
upstream test {
ip_hash;
server localhost:8080;
server localhost:8081;
}
Copy the code
4. Fair (third party)
Requests are allocated based on the response time of the back-end server, and those with short response times are allocated first. This configuration is for faster response to the user
upstream backend {
fair;
server localhost:8080;
server localhost:8081;
}
Copy the code
5. Url_hash (third party)
Requests are allocated based on the hash result of the accessed URL, so that each URL is directed to the same back-end server. This is effective when the back-end server is cached. “(upstream) add a hash statement while reading upstream. Do not write weight or other parameters in the server statement
upstream backend {
hash $request_uri;
hash_method crc32;
server localhost:8080;
server localhost:8081;
}
Copy the code
The above five load balancing modes are applicable to different situations, so you can choose which policy mode to use according to the actual situation. However, fair and URl_hash require third-party modules to be installed.
5. Separation of movement and movement
Separation of dynamic and static is to make dynamic web pages in dynamic websites distinguish constant resources from frequently changing resources according to certain rules. After the separation of dynamic and static resources, we can do cache operation according to the characteristics of static resources. This is the core idea of static website processing.
upstream web_servers { server localhost:8081; server localhost:8082; } server { listen 80; server_name localhost; set $doc_root /usr/local/var/www; location ~* \.(gif|jpg|jpeg|png|bmp|ico|swf|css|js)$ { root $doc_root/img; } location / { proxy_pass http://web_servers; Proxy_set_header Host $Host :$server_port; } error_page 500 502 503 504 /50x.html; location = /50x.html { root $doc_root; }}Copy the code
Sixth, other
1. The return instructions
Returns the HTTP status code and an optional second parameter can be the URL to redirect to
location /permanently/moved/url {
return 301 http://www.example.com/moved/here;
}
Copy the code
2. Rewrite the instructions
Rewriting a URI requests rewrite by modifying the request URI several times during request processing using the rewrite directive, which has one optional and two required parameters.
The first (required) parameter is the regular expression that the request URI must match.
The second parameter is the URI used to replace the matching URI.
An optional third parameter is a flag that can stop further processing of the rewrite instruction or send a redirect (code 301 or 302)
location /users/ { rewrite ^/users/(.*)$ /show? user=$1 break; }Copy the code
3. Error_page instructions
Using the error_page directive, you can configure NGINX to return a custom page with an error code, replace other error codes in the response, or redirect the browser to a different URI. In the following example, the error_page directive specifies the page (/404.html) to return the 404 page error code.
error_page 404 /404.html;
Copy the code
4. Log
Access log: Gzip compression needs to be enabled on; Otherwise, no log file is generated. Open the log_format and access_log comments
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /usr/local/etc/nginx/logs/host.access.log main;
gzip on;
Copy the code
5. Deny instructions
# blocking access to a directory location ~ * \. (TXT | doc) ${root $doc_root; deny all; }Copy the code
6. Built-in variables
The built-in variables that can be used in the nginx configuration file start with the dollar sign $and are also called global variables. The values of some predefined variables can be changed.
$args
:#
This variable is equal to the argument in the request line, same as$query_string
$content_length
: The content-Length field in the request header.$content_type
: Content-type field in the request header.$document_root
: The value specified in the root directive by the current request.$host
: Request host header field, otherwise server name.$http_user_agent
: Information about the client Agent$http_cookie
: Indicates client cookie information$limit_rate
: This variable can limit the connection rate.$request_method
: Action requested by the client, usually GET or POST.$remote_addr
: IP address of the client.$remote_port
: Indicates the port of the client.$remote_user
: User name that has been authenticated by the Auth Basic Module.$request_filename
: File path of the current request, generated by root or alias directives and URI requests.$scheme
: Indicates the HTTP method, such as HTTP or HTTPS.$server_protocol
: The protocol used by the request, usually HTTP/1.0 or HTTP/1.1.$server_addr
: Server address, which can be determined after a system call.$server_name
: Indicates the server name.$server_port
: The port at which the request reaches the server.$request_uri
: the original URI containing the request parameters, but not the host name, such as:”/foo/bar.php? arg=baz
“.$uri
: the current URI with no request parameters,$uri
Does not contain the host name, such as”/foo/bar.html
“.$document_uri
And:$uri
The same
The original link: blog.csdn.net/vbirdbest/a…
Copyright Notice: this article is written BY CSDN blogger “Vbirdbest” and is reproduced under THE CC 4.0 BY-SA copyright agreement. Please attach a link to the original source and this statement.
Recent hot articles recommended:
1.1,000+ Java interview questions and answers (the latest version of 2021)
2. Stop filling up the if/ else screen and try strategy mode.
3. Oh, my gosh! Xx ≠ NULL in Java
4.Spring Boot 2.5 is a blockbuster release. Dark Mode is a blast!
5. “Java Development Manual (Songshan version)” the latest release, speed download!
Feel good, don’t forget to click “like” + forward oh!