Home  >  Article  >  php教程  >  Do you really understand how to configure Nginx as a web server?

Do you really understand how to configure Nginx as a web server?

WBOY
WBOYOriginal
2016-12-01 00:00:251240browse

Do you really understand how to configure Nginx as a web server
Before reading, it is recommended to read First Introduction to Nginx. After that, let’s take a look at Nginx configuration.
In abstract terms, configuring Nginx as a web server is to define which URLS to process and how to process the requests corresponding to these URLS. Specifically, it is to define some virtual servers (Virtual Servers) to control requests with specific IP and domain names.
More specifically, Nginx controls the selection of URIS by defining a series of locations. Each location defines a processing scenario for the request mapped to itself: returning a file or proxy request, or returning different error pages based on different error codes. In addition, depending on the URI, the request can also be redirected to other servers or locations.
Set up a virtual server
listen:
The Nginx configuration file contains at least one server command, which is used to define a virtual server. When a request comes, Nginx will first select a virtual server to handle the request.
The virtual server is defined in server in the http context:
http { server { # Server configuration
}
}
Note: Multiple servers can be defined in http
The server configuration block uses the listen command to monitor the local IP and port number (including Unix domain socket and path). It supports IPv4 and IPv6. The IPv6 address needs to be enclosed in square brackets:
server { listen 127.0.0.1:8080; # IPv4 address, port 8080
# listen [2001:3CA1:10F:1A:121B:0:0:10]:80; # IPv6 address, port 80
# listen [::]:80; # Listen to all IPv4 and IPv6 addresses of this machine, port 80
# The rest of server configuration}
In the above configuration, if the port number is not written, port 80 will be used by default. If the IP is not written, all IPs of the local machine will be monitored.
server_name:
If the listen IPs and port numbers of multiple servers are exactly the same, Nginx will pass the Host in the request header
Do you really understand how to configure Nginx as a web server

Compare with the hostname defined by server_name to select the appropriate virtual server to handle the request:
server { listen 80;
server_name lufficc.com www.lufficc.com;
...
}
The parameters of server_name can be:
The complete hostname, such as: api.lufficc.com.
Contains wildcards (including *), such as: *.lufficc.com or api.*.
Regular expression, starting with ~.
Wildcard characters can only be at the beginning or end, and can only be adjacent to a . Neither www.*.example.org nor w*.example.org are valid. However, you can use regular expressions to match these names, such as ~^www..+.example.org$ and ~^w.*.example.org$ . And * can match multiple parts. The name *.example.org matches not only www.example.org but also www.sub.example.org.
For regular expressions: The regular expressions used by Nginx are compatible with the regular expressions used by the Perl programming language (PCRE). To use a regular expression, it must start with ~.
Named regular expressions can capture variables and then use:
server { server_name ~^(www.)?(?.+)$; location / { root /sites/$domain;
}
}
The content matched between parentheses () can also be referenced later by $1, and $2 represents the content in the second previous (). Therefore, the above content can also be written as:
server { server_name ~^(www.)?(.+)$; location / { root /sites/$2;
}
}
A server_name example:
server { listen 80;
server_name api.lufficc.com *.lufficc.com;
...
}
Likewise, if multiple names match the Host header, Nginx selects in the following order:
The complete hostname, such as api.lufficc.com.
The longest wildcard name starting with *, such as: *.lufficc.com.
The longest wildcard name ending with *, such as: api.*.
The first matching regular expression. (Follow the order in the configuration file)
That is, the priority: api.lufficc.com > *.lufficc.com > api.* > Regular.
If the Host header does not match any server_name, Nginx will route the request to the default virtual server. The default virtual server refers to: the first server in the nginx.conf file or explicitly declared with default_server:
server { listen 80 default_server;
...
}
Configure location
Matching of URI and location parameters
After selecting the server, Nginx will select the appropriate location based on the URIs to decide whether to proxy the request or return the file.
The location directive accepts two types of parameters:
prefix string (path name)
Regular expression
For prefix string parameters, URIs must strictly begin with it. For example, for the /some/path/ parameter, it matches /some/path/document.html, but does not match /my-site/some/path because /my-site/some/path does not start with /some/path/.
location /some/path/ {
...
}
For regular expressions, starting with ~ means case-sensitive, and starting with ~* means case-insensitive. Note that the . in the path should be written as . . For example, a location that matches URIs ending in .html or .htm:
location ~ .html? {
...
}
Regular expressions have higher precedence than prefix strings. If a matching prefix string is found, the search for the regular expression still continues, but if the prefix string begins with ^~ , the regular expression is no longer checked.
The specific search and matching process is as follows:
Compares the URI to all prefix strings.
The = modifier indicates that the URI must be equal (not start, but equal) to the prefix string, and if found, the search stops.
If the longest prefix matching string found begins with ^~, the regular expression is no longer searched for a match.
Stores the longest matching prefix string.
Test comparing URIs with regular expressions.
Stops after finding the first matching regular expression.
If there is no regular expression match, the location corresponding to the stored prefix string 4 is used.
The = modifier has the highest precedence. If the homepage of the website is visited frequently, we can specifically define a location to reduce the number of search matches (because searching for a matching location modified with = will stop the search) and improve the speed:
location = / {
...
}
Static files and proxies
The location also defines how to handle matching requests: return static files or hand them over to a proxy server. In the example below, the first location returns static files in the /data directory, and the second location passes the request to the server of the https://lufficc.com domain name for processing:
server { location /images/ { root /data;
} location / { proxy_pass https://lufficc.com;
}
}
The root directive defines the root directory of the static file and is concatenated with the URI to form the final local file path. For example, if /images/example.png is requested, the local server file /data/images/example.png will be returned after splicing.
The proxy_pass directive passes the request to the proxy server pointed to by the URL. The response from the proxy server is then forwarded to the client. In the above example, all requests for URIs that do not start with /images/ will be passed to the proxy server for processing.
For example, if I set proxy_pass to https://www.baidu.com/, then when I visit http://search.lufficc.com/, I will get the same response (page) as Baidu homepage (interested children's shoes can try searching by themselves) Function, no different from Baidu):
server{
listen 80;
server_name search.lufficc.com;
location / {
proxy_pass https://www.baidu.com;
}
}
Using Variables
You can use variables to make Nginx handle different requests differently. Variables are calculated at runtime and used as arguments to instructions. Variables are represented by symbols starting with $. Variables define information based on the state of Nginx, such as properties of the currently processed request.
There are many predefined variables, such as the core HTTP variables, and you can also define custom variables using the set, map and geo directives. Most variables are calculated at runtime and contain information related to a specific request. For example, $remote_addr contains the client IP address and $uri holds the current URI value.
Some commonly used variables are as follows:
Variable name function
$uri The current URI in the request (without request parameters), which can be modified through internal redirection or using the index directive. $uri does not contain the host name, such as /foo/bar.html.
$arg_name is the parameter name in the request, that is, arg_name in the form of arg_name=arg_value after "?"
$hostname hostname
$args Parameter values ​​in the request
$query_string same as $args
$request represents the client’s request address
$request_uri This variable is equal to the original URI containing some client request parameters. It cannot be modified and does not contain the host name, such as: /cnphp/test.php?arg=freemouse.
... ...
A simple application is to redirect from http to https with path information:
server{
... return 301 https://lufficc.com$request_uri;
...
}
Return specific status code
If some resources on your website are permanently removed, the fastest and most concise way is to use the return command to return directly:
location /wrong/url { return 404;
}
The first parameter of return is the response code. The optional second parameter can be the URL of the redirect (corresponding to codes 301, 302, 303, and 307) or the text returned in the response body. For example:
location /permanently/moved/url { return 301 http://www.example.com/moved/here;
}
The return directive can be included in location and server contexts:
server{
location / { return 404;
}
}
Or:
server{
...return 404;
location / {
...
}
}
Error handling
The error_page command can configure an error page for a specific error code, or redirect to other pages. The following example will return the /404.html page when a 404 error occurs.
error_page 404 /404.html;
The error_page command defines how errors are handled, so it does not return directly, whereas return does return immediately. When the proxy server or Nginx generates corresponding error codes during processing, the corresponding error page will be returned.
In the example below, when Nginx cannot find the page, it replaces code 404 with code 301 and redirects the client to http://example.com/new/path.html. This configuration is useful, for example, when a client is still trying to access the page with the old URI. The 301 code informs the browser that the page has been permanently removed and needs to be automatically replaced with the new address returned.
location /old/path.html { error_page 404 =301 http:/example.com/new/path.html;
}
Rewrite URIs
The rewrite directive can modify the requested URI multiple times. The first parameter of rewrite is the regular expression that the URI needs to match, and the second parameter is the URI to be replaced. The third parameter is optional and indicates whether to continue to override or return a redirection code (301 or 302). For example:
location /users/ { rewrite ^/users/(.*)$ /show?user=$1 break;
}
You can include multiple rewrite directives in the server and location contexts. Nginx executes instructions one by one in the order they occur. When server is selected, the rewrite directive in server will be executed once.
After Nginx processes a set of rewrite directives, it selects a location based on the new URI. If the selected location still contains rewrite directives, they will be executed in sequence. If the URI matches all, a new location is searched after all defined rewrite directives have been processed.
The following example uses the rewrite directive with the return directive:
server {
...
rewrite ^(/download/.*)/media/(.*)..*$ $1/mp3/$2.mp3 last;
rewrite ^(/download/.*)/audio/(.*)..*$ $1/mp3/$2.ra last; return 403;
...
}
URIs such as /download/some/media/file are changed to /download/some/mp3/file.mp3 . Due to the last flag, subsequent instructions (the second rewrite directive and the return directive) are skipped, but Nginx continues to process the request with the changed URI. Similarly, a URI such as /download/some/audio/file is replaced with /download/some/mp3/file.ra. If the URI does not match the rewrite directive, Nginx returns a 403 error code to the client.
The difference between last and break is:
last : Stops execution of rewrite directives in the current server or location context, but Nginx continues searching for a location that matches the rewritten URI and applies any rewrite directives in the new location (which means the URI may change again).
break : Stops processing of the rewrite directive in the current context and cancels the search for a location matching the new URI. The rewrite directive in the new location will not be executed.
Appendix
Commonly used regular rules
. : Matches any character except newline
?: Repeat 0 or 1 times
+ : Repeat 1 or more times
*: Repeat 0 or more times
d: Match numbers
^ : Matches the beginning of a string
$: Introduction to matching strings
{n}: Repeat n times
{n,}: Repeat n times or more
[c]: Matches the single character c
[a-z]: Match any one of the lowercase letters a-z
Global variables
$args: #This variable is equal to the parameters in the request line, the same as $query_string
$content_length: 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.
$host : Request host header field, otherwise the server name.
$http_user_agent: Client agent information
$http_cookie: Client cookie information
$limit_rate: This variable can limit the connection rate.
$request_method: The action requested by the client, usually GET or POST.
$remote_addr: The client’s IP address.
$remote_port: The client's port.
$remote_user: Username that has been authenticated by Auth Basic Module.
$request_filename: The file path of the current request, generated by the root or alias directive and URI request.
$scheme: HTTP method (such as http, https).
$server_protocol: The protocol used by the request, usually HTTP/1.0 or HTTP/1.1.
$server_addr: Server address, this value can be determined after completing a system call.
$server_name: Server name.
$server_port: The port number where the request reaches the server.
$request_uri: The original URI containing the request parameters, excluding the host name, such as: /foo/bar.php?arg=baz.
$uri: The current URI without request parameters, $uri does not contain the host name, such as /foo/bar.html.
$document_uri: Same as $uri.
For example request: http://localhost:88/test1/test2/test.php
$host: localhost
$server_port:88
$request_uri: http://localhost:88/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test2/test.php

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn