Nginx itself is also a static resource server, when only static resources, you can use Nginx to do the server, if a website is only a static page, then you can use this way to achieve deployment.

/usr/local/var/ WWW = /usr/local/var/ WWW = /usr/local/var/ WWW = /usr/local/var/ WWW

2. Configure the 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 tests

http://localhost/ points to/usr/local/var/WWW/index HTML, Index.html is the HTML http://localhost/test.html to install nginx/usr/local/var/WWW/HTML/test. The HTML note: Nginx. conf: #user nobody; For Linux, change to user root; Change this parameter to user in macOS. Then reload the configuration file or restart it and try again. The user name can be viewed using the who am I command.

4. Introduction to instructions

  • Server: Used to define services. HTTP can have multiple server blocks
  • Listen: Specifies the IP address and port on which the server listens for requests. If the IP 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 used for the configuration domain name
  • location : A server can have multiple locations, followed by a URI, which can be a regular expression. / means to match any path. When the client accesses a path that meets this URI, the code in the Location block will be executed
  • root : Root, when accessing http://localhost/test.html, “/ test. The HTML will match” to “/” uri, find the root is/usr/local/var/WWW/HTML, Users to access resources physical address = root + uri = / usr/local/var/WWW/HTML + / test. The HTML = / usr/local/var/WWW/HTML/test. The HTML
  • Server_name = server_name = server_name = server_name = server_name = server_name = server_name = server_name If no specific file is specified in the access path, the resource set by index is returned. If http://localhost/html/ is accessed, index.html is returned by default

Location URI Regular expression

  • . : Matches any character except newline
  • ? : Repeat 0 or 1 times
    • : Repeat 1 or more times
    • : Repeat 0 or more times
  • \ D: Match the number
  • ^ : Matches the beginning of the string
  • $: The end of the matching string
  • {n} : repeat n times
  • {n,} : repeat n or more times
  • [c] : matches a single character c
  • [a-z] : matches any of the lowercase letters a-Z
  • (a | b | c) : line means to match any kind of situation, each case using the vertical bar space, generally use small brackets, wrap, fit to conform to a character or string of characters b or c characters
  • \ Backslash: Used to escape special characters

Matches between the parentheses () can be passed later

1 to quote,

1 is used as a reference, and 2 refers to the content of the previous second (). A confusing part of the re is escaping special characters.

Second, static server In the company often encounter static server, usually provides an upload function, other applications need static resources from the static server.

Create images and img directories under /usr/local/var/www, and place a test.jpg file under 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 variable using set instruction, syntax set variable name value; References use variable name values; References use variable names; The doc_root variable is customized here.

Static server location mapping generally has two ways:

Use path, like/images/pictures will be on a picture directory, use the suffix, such as the JPG,. PNG, suffix matched pattern to 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 normal character exact matching. So it’s a perfect match.
  • ^~ The prefix matches. If the match is successful, no more locations will be matched.
  • ~ indicates that a regular match is performed, which is case sensitive
  • ~* indicates that a regular match is performed, case insensitive
  • / XXX/Regular string path match
  • / universal match. Any request will be matched

Location priority When a path matches multiple locations, there is a precedence order for which location can be matched. The precedence order depends on the expression type of location value, and does not depend on the order in the configuration file. Expressions of the same type are matched preferentially with strings of length. Java interview questions

Here are the instructions in order of priority:

The equal sign type (=) has the highest priority. Once a match is successful, the search stops. ^ Type expression that is not a regular expression. Once a match is successful, the search stops. Priority of the regular expression type (~*). If more than one location regex matches, the one with the longest regular expression is used. General string matching type. Match by prefix. / Universal match, if no match is found, match universal priority search problem: Different types of location maps determine whether to continue searching down

Regular expression type (~*). Regular string matching type/XXX / : searches other locations until the highest priority is found, or the search stops when the first case is found

Location Indicates the highest priority:

(location =) > (location ^~ path) > (location ~,~* regular order) > (location partial start path) > (/) location = / {# Matches exactly /, no strings after the host name / [configuration A]} location / {# Matches all requests starting with A /. # But if there is a longer expression of the same type, select the longer expression. If there is a regular expression to match, the regular expression will be matched first. [configuration B]} Location /documents/ {# match all requests that start 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, the regular expression will be matched 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/ {# character matches /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

Reverse Proxy Reverse Proxy is probably the most used function of Nginx. In Reverse Proxy mode, a Proxy server is used to accept Internet connection requests and then forward the requests to a server on the internal network. The proxy server acts as a reverse proxy server when the result obtained from the server is returned to the Internet client.

In simple terms, 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 and resides on the same network environment as the real server, of course, it may be the same server with different ports.

The reverse proxy is implemented by the proxy_pass directive.

Start a Java Web project with 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 are accessing localhost:8081

Load balancing is also a common function of Nginx. Load balancing means that the execution of load balancing is distributed among multiple operation units, such as Web server, FTP server, enterprise critical application server, and other critical task servers, so as to complete the work together.

In simple terms, when two or more servers are deployed, requests are randomly distributed to the specified server for processing based on rules. In load-balancing configuration, a reverse proxy must be configured at the same time to switch to load balancing. Nginx currently supports three load balancing policies and two common third-party policies.

Load balancing is done through the upstream directive.

  1. RR (round robin: polling 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, That is, the ratio of requests received by the server is 1:1. If the back-end server goes down, the request is automatically removed. Polling is the default configuration and does not require much configuration

The same project starts with 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

  1. Weight specifies the polling probability. Weight is proportional to the access ratio, that is, the ratio of the server to receive requests is the ratio of the configured weight. It is used in the case of uneven performance of the back-end server, such as the server performance is almost less receiving point requests, and the server performance is better than processing point requests.

    upstream test { server localhost:8081 weight=1; server localhost:8082 weight=3; server localhost:8083 weight=4 backup; }

The example is that only one of the four requests is allocated to 8081 and the other three are allocated to 8082. Backup refers to hot backup. 8083 will be run only when 8081 and 8082 are down

  1. The problem with both methods of ip_hash is that the next request may be sent to another server. When our application is not stateless (session is used to store data), there is a big problem, such as storing login information in session. Therefore, it is necessary to re-log in when switching to another server. In most cases, we need a client to access only one server, so we need to use iphash. Each request of iphash is allocated according to the hash result of access IP, so that each visitor has a fixed access to the back-end server, which can solve the session problem.

    upstream test { ip_hash; server localhost:8080; server localhost:8081; }

  2. Fair (third party) allocates requests based on the response time of the back-end server, with priority given to those with short response times. This configuration is designed to give faster response to the user

    upstream backend { fair; server localhost:8080; server localhost:8081; }

  3. Url_hash (third-party) Allocates requests based on the hash result of the url, so that each URL is directed to the same backend server, which is more efficient when the backend server is cached. (10) Add the hash to upstream. (10) Do not write weight or other parameters to server. (10) Hash_method is the hash algorithm used

    upstream backend { hash $request_uri; hash_method crc32; server localhost:8080; server localhost:8081; }

The preceding five load balancing modes are applicable to different scenarios. Therefore, you can choose the policy mode based on the actual situation. However, fair and URl_hash can be used only after third-party modules are installed.

Five, static separation static separation is to let the dynamic web page in the dynamic website according to certain rules to the constant resources and often change the resources, dynamic resources split, we can do according to the characteristics of the static resources cache operation, this is the core idea of static site 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

1. The return directive returns the HTTP status code and the optional second argument can be the REdirected URL

location /permanently/moved/url {
    return 301 http://www.example.com/moved/here;
}
Copy the code

2. The rewrite directive rewriting the URI requests rewrite, modifying the request URI multiple times during request processing using the rewrite directive, which has one optional parameter and two required parameters.

The first (required) argument 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 the processing of further rewriting instructions or send redirects (codes 301 or 302)

location /users/ { rewrite ^/users/(.*)$ /show? user=$1 break; }Copy the code

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 another URI. In the following example, the error_page directive specifies the page on which the 404 page error code is to be returned (/404.html).

error_page 404 /404.html;

4. Log access logs: Enable gzip on compression. Otherwise, no log file is generated and the log_format and access_log annotations are enabled

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

Built-in variables Nginx configuration files can use built-in variables starting with the dollar character $, also known as global variables. The values of some predefined variables can be changed.

Args: # This variable is equal to the argument in the request line and is the same as query_string content_LENGTH: Content− Length field in the request header. Content \_length: Content-length field in the request header. 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 for the current request. Document \_root: the value specified in the root directive for the current request. Document_root: The value specified in the root directive for the current request. Host: requests the host header field, otherwise, the server name. Http_user_agent: client agent information HTTP \_user\_agent: client agent information http_user_agent: client agent information http_cookie: client cookie information limit_rate: This variable can limit the connection rate. Limit \_rate: This variable can limit the connection rate. Limit_rate: This variable can limit the connection rate. Request_method: Action requested by the client, usually GET or POST. Remote_addr: indicates the IP address of the client. Remote \_addr: indicates the IP address of the client. Remote_addr: indicates the IP address of the client. Remote_port: indicates the port of the client. Remote_user: user name authenticated by AuthBasicModule. Remote \_user: user name authenticated by the Auth Basic Module. Remote_user: user name authenticated by AuthBasicModule. Request_filename: The file path of the current request, generated by the root or alias directive and the URI request. Scheme: HTTP (such as HTTP or HTTPS). Scheme: HTTP (such as HTTP or HTTPS). Scheme: HTTP (such as HTTP or HTTPS). Server_protocol: Protocol used for the request, usually HTTP/1.0 or HTTP/1.1. Server_addr: Server address, which can be determined after a system call. Server \ _ADDR: Server address, which can be determined after a system call. Server_addr: Server address, which can be determined after a system call. Server_name: indicates the server name. Server_port: port number for the request to reach the server. Server \_port: port number for the request to reach the server. Server_port: port number for the request to reach the server. Request_uri: the original URI containing the request parameters, excluding the host name, e.g. “/foo/bar.php? Arg = baz “.

Uri: the current URI with no request parameters,

Uri: The current URI with no request parameters. The URI does not contain a host name, such as /foo/bar.html.

Document_uri:

Documenturi: Is the same as the URI