“This is the 7th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

The set command

This directive sets a new variable.

grammar set $variable value;
The default value
location server,location,if

Variable: The name of a variable that starts with “$” and must not have the same name as a default global variable on the Nginx server.

Value: Indicates the value of a variable. The value can be a string, other variables, or a combination of variables.

Rewrite commonly used global variables

variable instructions
$args Variable holds the request directive in the request URL. Such ashttp://192.168.200.133:8080?arg1=value1&arg$query_string = arg1=value1&arg2=value2
$http_user_agent The variable stores proxy information about the user accessing the service (if accessed through a browser, the browser version information is recorded)
$host The server_name variable stores the value of the access server
$document_uri The variable stores the URI of the currently accessed address. Such as/ server in “http://192.168.200.133/server?id=10&name=zhangsan”, the function and $uri
$document_root This variable stores the root value for the location of the current request. If not set, it points to the Nginx HTML directory by default
$content_length The content-Length variable stores the content-Length value in the request header
$content_type The content-Type variable stores the content-Type value in the request header
$http_cookie The variable stores the client’s cookie information. You can add cookie data by running add_header Set- cookie ‘cookieName=cookieValue’
$limit_rate The limit_rate directive is set in the Nginx configuration. The default value is 0 and there is no limit.
$remote_addr The variable stores the IP address of the client
$remote_port Variable stores the port number for the connection between the client and the server
$remote_user The user name of the client is stored in the variable, which can be obtained only by the authentication module
$scheme The access protocol is stored in the
$server_addr The server address is stored in the variable
$server_name Variable stores the name of the server to which the client request arrived
$server_port The port number for the client request to reach the server is stored in the variable
$server_protocol The version of the client request protocol, such as “HTTP/1.1”, is stored in the variable.
$request_body_fifile Variable stores the name of the local file resource sent to the back-end server
$request_method Variables store client requests, such as “GET”,”POST”, etc
$request_fifilename Variable that stores the pathname of the currently requested resource file
$request_uri A variable stores the URI of the current request and carries the request parameters, such ashttp://192.168.200.133/server?id=10&name=zhangsan in the “/ server? Id = 10 & name = zhangsan”

If the instructions

This directive is used to support conditional judgment and select different Nginx configurations based on the result of the conditional judgment.

grammar if(condition){… }
The default value
location server,location

Condition is the judgment condition, which can be written as follows:

1. Variable name. If the value corresponding to the variable name is null or 0, if is false, all other conditions are true.

if ($param){

}
Copy the code

2. Use “=” and “! =” Compares whether a variable and a string are equal, true if they are equal, false if they are not

if ($request_method = POST){ 
  return 405; 
}
Copy the code

Note: The difference here is that strings don’t need quotes.

3. Use a regular expression to match variables. Returns true if the match succeeds, false otherwise. Use “”,” “,”! “between variables and regular expressions. “, “!” To connect to.

“~” indicates case-sensitive regular expression matching.

“~*” indicates that regular expression matching is case insensitive

! “” “And”! *” returns false if matched, true if not

if ($http_user_agent ~ MSIE){ 
  Whether the value of #$http_user_agent contains the MSIE string, return if it does
  true 
}
Copy the code

Note: Regular expression strings generally do not need to be quoted, but if the string contains either “}” or “;” And so on, you need to put quotes around it.

4, check whether the requested file exists using “-f” and “! -f”,

When using “-f”, return true if the requested file exists, false if it does not. When using “!” F “returns true if the requested file does not exist but the directory in which the file resides, false if neither file nor directory exists, or false if the file exists

if (-f $request_filename){ 
  Check whether the requested file exists
}
if(! -f $request_filename){Check whether the requested file does not exist
} 
Copy the code

5. Check whether the requested directory exists using “-d” and “! -d”,

When “-d” is used, if returns true if the requested directory exists and false if it does not

When using “!” -d” returns true if the requested directory does not exist but its parent directory does, false if neither the parent directory nor the requested directory exists, or false if the requested directory does exist.

6. Check whether the requested directory or file exists using “-e” and “! -e” When “-e” is used, if returns true if the requested directory or file exists, otherwise false.

7. Determine whether the requested file is executable using “-x” and “! -x”

When using “-x”, if returns true if the requested file is executable, false otherwise

When using “!” -x”, returns true if the requested file is not executable, false otherwise

Break the instructions

This directive is used to interrupt other Nginx configurations currently in the same scope. In Nginx configurations in the same scope as this directive, the directives before it take effect, and those after it take effect.

grammar break;
The default value
location server,location,if

Example:

location/ {if ($param){ 
  set $id The $1; 
  break; 
  limit_rate 10k; }}Copy the code

The return instructions

This directive completes the processing of the request and returns the response status code directly to the client. All Nginx configurations after return are invalid.

grammar return code [text];

return code URL;

return URL;
The default value
location server,location,if

Code: proxy for the HTTP status returned to the client. Can return any HTTP status proxy with status codes 0 to 999

Text: the body content of the response returned to the client, supporting the use of variables

URL: indicates the URL returned to the client

Rewrite instructions

This directive changes the URI through the use of regular expressions. There can be one or more directives that match and process urls in sequence.

The module used by this directive is ngx_HTTP_rewrite_module.

The ngx_HTTP_rewrite_module module is used to change the request URI using PCRE regular expressions, return redirects, and conditionally select configurations.Copy the code

The difference between a URL and a URI

URI: Unified Resource Identifier URL: Unified resource locatorCopy the code
grammar rewrite regex replacement [flag];
The default value
location Server, location, if

Write to the server block of the configuration file, as follows:

server {
    rewriteRule-oriented path rewrite type; }Copy the code

Regex (rule): regular path cross-border expression used to match URIs

Replacement: A string used to replace the intercepted content in the URI after a successful match. If the string starts with “http://” or “https://”, no further processing is performed on the URI, but the overwritten URI is returned to the client.

Flag (rewrite type): sets the behavior of rewrite on urIs. The options are as follows:

Last: After this rule is matched, continue to match the new location URL rule. Last is written in server and if, while break is written in location.

Break: This rule is terminated when the match is complete and no further rules are matched.

Redirect: Returns 302 temporary redirect. The browser address displays the new URL address.

Permanent: returns 301 permanent redirection. The browser address displays the new URL address.

For example, here’s an example:

rewrite^ / (. *) http://www.baidu.com/The $1 permanent;
Copy the code

Description:

Rewrite is the fixed keyword, indicating the start of the rewrite matching rule. The regex for ^ / (. *). This is a regular expression that matches the full domain name and the following path address. Replacement is www.baidu.com/1, which is 1… Flag is permanent, indicating permanent redirection, that is, redirecting to www.baidu.com/$1.

A simple example

server {
    # When accessing /last.html, the page content is rewritten to /index.html
    rewrite /last.html /index.html last;
  
    # When accessing /break.html, the page content is rewritten to /index.html and subsequent matching is stopped
    rewrite /break.html /index.html break;
  
    # when accessing /redirect. HTML, the page is directed to /index.html
    rewrite /redirect.html /index.html redirect;
  
    # when accessing /permanent. HTML, the page is directed 301 to /index.html
    rewrite /permanent.html /index.html permanent;
  
    # put/HTML /*.html => /post/*.html, 301 directed
    rewrite^/html/(.+?) .html$ /post/The $1.html permanent;
  
    /search/key => /search.html? keyword=key
    rewrite^/search\/([^\/]+?) (\ | / $)/search.html? keyword=The $1 permanent;
}
Copy the code

The difference between last and break

301 and 302 cannot simply return a status code. They must also have a redirected URL. This is why the return directive cannot return 301,302. Here the difference between last and break is a little difficult to understand:

  • Last is written in server and if, while break is written in location
  • Last does not terminate the rewritten URL matching, that is, the new URL will go through the matching process again from the server, while break terminates the rewritten URL matching
  • Both break and last prevent further execution of the rewrite directive

If a break is returned in a location, it immediately takes effect and stops subsequent matching of locations

server {
    location / {
        rewrite /last/ /q.html last;
        rewrite /break/ /q.html break;
    }
    location = /q.html {
        return 400; }}Copy the code
  • access/last/To rewrite/q.htmlAnd then use the new oneuriAnd then I match it. I match itlocatoin = /q.htmlAnd then it goes back400
  • access/breakTo rewrite/q.htmlBecause of the returnbreak“, just stopped

Rewrite_log instruction

This command configures whether to enable the output function of URL rewrite logs.

grammar rewrite_log on | off;
The default value rewrite_log off;
location HTTP, server, location, if

After this function is enabled, logs related to URL rewriting are output at the notice level to the log file summary configured by the error_log command.

Independent domain

A complete project contains multiple modules, such as the shopping website commodity search module, commodity details module and shopping cart module, so how do we set an independent domain name for each module.

Requirements:

http://search.hm.com visit the product search module http://item.hm.com visit the product details module http://cart.hm.com visit the shopping cart moduleCopy the code
server{ 
  listen 80; 
  server_name search.abc.com; 
  rewrite^ (. *) http://www.abc.com/bbsThe $1 last; 
}
server{ 
  listen 81;
  server_name item.abc.com; 
  rewrite^ (. *) http://www.abc.com/itemThe $1 last;
}
server{ 
  listen 82; 
  server_name cart.abc.com; 
  rewrite^ (. *) http://www.abc.com/cartThe $1 last; 
} 
Copy the code

Directory automatically adds “/”

Problem description

Use an example to illustrate the problem:

server { 
  listen 80; 
  server_name localhost; 
  location / { 
    root html; 
    indexindex.html; }}Copy the code

To access the above resources, it is as simple as going to http://192.168.1.100 directly. The address does not need to be followed by a /, but if you change the above configuration to the following:

server { 
  listen 80; 
  server_name localhost; 
  location /hm { 
    root html; 
    indexindex.html; }}Copy the code

At this point, if you want to access the above resources, you can go to http://192.168.1.100/hm/ as described above, but if the address is not followed by a slash, the page will have a problem. If not add slashes, nginx server internal will automatically do a 301 redirect, redirection address there will be a instruction is called server_name_in_redirect on | off; To determine the redirection address:

If the command is on, the redirection address is: http://server_name/ directory name/; If the command is off, the redirection address is http:// domain name/directory name/in the original URL.Copy the code

If the server_name_in_redirect is set to ON, If the value is off, the 301 redirection address changes to http://192.168.1.100/hm/. The back one is normal, the front one is wrong.

Note that the server_name_in_redirect directive used to be on by default before Nginx 0.8.48, then changed to off, so we don’t need to worry about that now. But if it was pre-0.8.48 and server_name_in_redirect was set to ON, how do we fix this with rewrite?

The solution

You can use the rewrite functionality to automatically add a slash to a URL without a trailing slash.

server { 
  listen 80; 
  server_name localhost; 
  server_name_in_redirect on; 
  location /hm { 
    if (-d $request_filename){ 
    rewrite^ / (. *) ([^ /]) $ http://$host/The $1$2/  permanent; }}}Copy the code

Merge directory

Search engine optimization (SEO) is a method of using search engine rules to provide information about the search engine ranking of a destination site. There are many ways in which we can effectively provide a degree of SEO when creating our own site. One will contain the URL directory hierarchy generally not more than three layers, otherwise not conducive to the search engine’s search also brought burden to the client’s input, but put all the files in a directory and can lead to file resource management confusion and the speed of access to the file will also increase as file and slow down, the two problems are contradictory, So how does rewrite solve this problem?

For example, the website has a resource file access path/server / 11/22/33/44/20. HTML, that is, exists in the HTML 5 level directory, if you want to access the resource file, the client URL is www.web.name/server/11/2…

server { 
  listen 80; 
  server_name www.web.name; 
  location /server{ 
    roothtml; }}Copy the code

But this is very bad for SEO search engine optimization, and the client is not easy to remember. Using rewrite we can configure this:

server { 
  listen 80; 
  server_name www.web.name; 
  location /server{ 
    rewrite ^/server-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /server/The $1/$2/$3/$4/A $5.html last; }}Copy the code

In this case, the client simply needs to type www.web.name/server-11-2…