Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure Nginx as a Web server

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "how to configure Nginx as a Web server". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to configure Nginx as a Web server.

In the abstract, configuring Nginx as a Web server defines which URLS to process and how to handle requests corresponding to these URLS. Specifically, some virtual servers (Virtual Servers) are defined to control requests with specific IP and domain names.

More specifically, Nginx controls the choice of URIS by defining a series of locations. Each location defines a scenario for processing requests that map to itself: return a file or proxy request, or return a different error page depending on the error code. In addition, depending on the URI, the request can also be redirected to another server or location.

Set up a virtual server

Listen:

The Nginx configuration file contains at least one server command that defines the virtual server. When a request arrives, Nginx first selects a virtual server to process the request.

The virtual server is defined in the server in the http context:

Http {server {# Server configuration}}

Note: multiple server can be defined in http

The server configuration block uses the listen command to listen for native IP and port numbers (including Unix domain socket and path). Support for IPv4 and IPv6,IPv6 addresses needs to be enclosed in square brackets:

Server {listen 127.0.0.1 server 8080; # IPv4 address, 8080 port # listen [2001:3CA1:10F:1A:121B:0:0:10]: 80; # IPv6 address, 80 port # listen [:]: 80; # listen to all IPv4 and IPv6 addresses of the machine, port 80 # The rest of server configuration}

In the above configuration, port 80 is used by default if the port number is not written, and all local IP is monitored if IP is not written.

Server_name:

If the listen IP and port number of multiple server are exactly the same, Nginx passes the Host in the request header

Compare with the hostname defined by server_name to select the appropriate virtual server to process the request:

Server {listen 80; server_name lufficc.com www.lufficc.com;.}

The parameters of server_name can be:

1. Complete host name, such as api.lufficc.com.

2. Contains wildcards (including *), such as * .lufficc.com or api.*.

3. Regular expression, starting with ~.

Wildcards can only be at the beginning or end, and can only be associated with one. Adjacent. Both www.*.example.org and w*.example.org are invalid. 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 those 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 matching between parentheses () can also be referenced later by $1, which represents the content in the second () above. Therefore, the above content can also be written as:

Server {server_name ~ ^ (www\.)? (. +) $; location / {root / sites/$2;}}

An example of server_name:

Server {listen 80; server_name api.lufficc.com * .lufficc.com;...}

Similarly, if more than one name matches the Host header, Nginx is selected in the following order:

1. Complete hostname, such as api.lufficc.com.

2. The longest wildcard name that begins with *, such as * .lufficc.com.

3. The longest wildcard name that ends with *, such as api.*.

4. * matching regular expressions. (in the order in the configuration file)

That is, priority: api.lufficc.com > * .lufficc.com > api.* > regular.

If the Host header does not match any of the server_name, Nginx routes the request to the default virtual server. The default virtual server refers to * 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

When the server is selected, the Nginx will choose the appropriate location based on the URIs to determine the proxy request or the return file.

The location directive accepts two types of parameters:

1. Prefix string (path name)

2. Regular expression

For prefix string parameters, URIs must strictly start with it. For example, for the / some/path/ parameter, you can match / some/path/document.html, but not / my-site/some/path, because / my-site/some/path does not start with / some/path/.

Server {listen 80 default_server;...}

For regular expressions, starting with ~ means case-sensitive and ~ * means case-insensitive. Pay attention to the one in the path. It should be written as\. . For example, a location that matches a URI that ends in .html or .htm:

Location ~\ .html? {.}

Regular expressions take precedence over prefix strings. If a matching prefix string is found, the search for the regular expression continues, but if the prefix string begins with ^ ~, the regular expression is no longer checked.

The specific search matching process is as follows:

1. Compare URI with all prefix strings.

The = modifier indicates that URI must be equal to the prefix string (not starting, but equal), and if found, the search stops.

3. If the longest prefix matching string found begins with ^ ~, the regular expression is no longer searched for a match.

4. Store the longest prefix string that matches.

5. Test and compare URI with regular expressions.

6. Stop after finding * matching regular expressions.

7. If there is no regular expression match, use the location corresponding to the prefix string stored in 4.

The = modifier has a priority of *. If the home page of a website is visited frequently, we can define a location to reduce the number of search matches (because the search for a = modified match will stop the search) and improve the speed:

Location = / {.}

Static files and agents

Location also defines how to handle matching requests: returning static files or handing them over to a proxy server. In the following example, * 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 splices with URI to form the final local file path. If the request / 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 that the URL points to. Let the response from the proxy server be forwarded to the client. In the above example, all requests for URI that do not start with / images / are passed to the proxy server for processing.

For example, if I set proxy_pass to https://www.baidu.com/, then visiting http://search.lufficc.com/ will get the same response (page) as Baidu's home page (interested children's shoes can try the search function themselves, which is no different from Baidu):

Server {listen 80; server_name search.lufficc.com; location / {proxy_pass https://www.baidu.com;}}

Use variables (Variables)

You can use variables to make Nginx process differently for different requests. Variables are calculated at run time and are used as arguments to instructions. Variables are represented by symbols that begin with $. The variable defines information based on the state of the Nginx, such as the properties of the request currently being processed.

There are many predefined variables, such as the core HTTP variable, and you can also use set,map and geo directives to define custom variables. Most variables are evaluated at run time and contain information related to a particular request. For example, $remote_addr contains the client IP address, and $uri holds the current Uri value.

Some commonly used variables are as follows:

A simple application is to redirect from http to https with path information:

Server {... Return 301 https://lufficc.com$request_uri;...}

Returns a specific status code

If some resources on your site are removed, the quickest and simplest way is to use the return command to return directly:

Location / wrong/url {return 404;}

The * parameters of return are the response codes. The second optional parameter can be the URL of the redirect (corresponding to codes 301302303 and 307) or the text returned in the response body. For example:

Location / permanently/moved/url {return 301 http://www.example.com/moved/here;}

Return directives 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 with a specific error code or redirect to another page. The following example returns the / 404.html page when a 404 error occurs.

Error_page 404 / 404.html

The error_page command defines how to handle errors, so it doesn't return directly, and return does return immediately. When the proxy server or Nginx processes the corresponding error code, the corresponding error page will be returned.

In the following example, 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, such as when the client is still trying to access the page with the old URI, the 301 code informs the browser that the page has been removed and needs to be automatically replaced with the new address returned.

Location / old/path.html {error_page 404 = 301http:/example.com/new/path.html;}

Rewrite URIs

The rewrite directive can modify the requested URI multiple times. The * parameters of rewrite are the regular expressions that URI needs to match, and the second parameter is the URI to be replaced. The third parameter, optional, indicates whether you can continue to rewrite or return the redirection code (301 or 302). For example:

Location / users/ {rewrite ^ / users/ (. *) $/ show?user=$1 break;}

You can include multiple rewrite instructions in the context of server and location. Nginx executes instructions one by one in the order in which they occur. When server is selected, the rewrite instruction in server is executed once.

After Nginx processes a set of rewrite instructions, it selects location based on the new URI. If the selected location still contains rewrite instructions, they will be executed in turn. If the URI matches all, the new rewrite is searched after all the defined location instructions 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;.}

URI such as / download/some/media/file is changed to / download/some/mp3/file.mp3. Subsequent instructions (the second rewrite instruction and the return instruction) are skipped due to the last flag, but Nginx continues to process the request with the changed URI. Similarly, URI such as / download/some/audio/file is replaced with / download/some/mp3/file.ra. If the URI does not match the rewrite instruction, Nginx returns the 403 error code to the client.

The differences between last and break are:

Last: stops executing the rewrite instruction in the current server or location context, but Nginx continues to search for a location that matches the rewritten URI and applies any rewrite instructions in the new location (which means that the URI may change again).

Break: stops the processing of the rewrite instruction in the current context and cancels the search for location that matches the new URI. The rewrite instruction in the new location is not executed.

Appendix

Commonly used regularity

Match any character except the newline character

?: repeat 0 or 1 times

+: repeat 1 or more times

*: repeat 0 or more times

\ d: match the number

^: match 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

[amurz]: matches any of the lowercase letters of amurz

Global variable

$args: # this variable is equal to the parameter in the request line, same as $query_string

$content_length: the Content-length field in the request header.

$content_type: the Content-Type field in the request header.

Document_root: the value specified in the root directive for the current request.

$host: request the host header field, otherwise it is the server name.

$http_user_agent: client agent information

$http_cookie: client cookie information

$limit_rate: this variable limits the connection rate.

Request_method: the action requested by the client, usually GET or POST.

Remote_addr: the IP address of the client.

Remote_port: the port of the client.

Remote_user: the user name 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 the URI request.

$scheme: the 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, which can be determined after completing a system call.

$server_name: server name.

Server_port: the port number on which the request arrives at the server.

$request_uri: the original URI that contains the request parameters, without the hostname, such as: / foo/bar.php?arg=baz.

$uri: the current URI,$uri without request parameters does not contain a hostname, 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:/test1/test2/test.php

$document_uri:/test1/test2/test.php

$document_root:/var/www/html

$request_filename:/var/www/html/test1/test2/test.php

At this point, I believe you have a deeper understanding of "how to configure Nginx as a Web server". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report