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

Explain in detail the redirection configuration and practice of Rewrite in Nginx

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

One: understand the meaning of address rewriting and address forwarding.

Address rewriting and address forwarding are two different concepts.

Address rewriting is to standardize addresses. For example, we can enter www.baidu.com in the address bar. We can also type www.baidu.cn. Will eventually be rewritten on www.baidu.com. The browser's address bar also displays www.baidu.com.

Address forwarding: it refers to the process by which the device checks the packet address and forwards the data to the nearest local area network after the data packet arrives at the router or bridge during the network data transmission.

So there are the following differences between address rewriting and address forwarding:

1. Address rewriting changes the address in the browser so that it is rewritten to the latest address in the browser. And address forwarding will not change the address of the browser.

two。 Address rewriting produces two requests, while address forwarding has only one request.

3. Address forwarding generally occurs within the same site project, while address rewriting is unrestricted.

4. Address forwarding is faster than address redirection.

Second: understand the use of Rewrite instructions

This instruction changes the URI through the use of regular expressions. One or more instructions can exist at the same time. URL needs to be matched and processed sequentially.

This directive can be configured in a server block or a location block, and its basic syntax structure is as follows:

Rewrite regex replacement [flag]

The meaning of rewrite: this instruction is an instruction that implements URL rewriting.

The meaning of regex: a regular expression used to match URI.

Replacement: replace the content to which the regex regular matches with replacement.

Flag: flag tag.

Flag has the following values:

Last: after the matching of this rule is complete, continue to match the new location URI rule down. (rarely used) break: this rule is terminated upon completion of the match, and no longer matches any subsequent rules (not commonly used). Redirect: returns the temporary redirection of 302, and the browser address will show the new URL address of the jump. Permanent: returns 301 permanent redirection. The browser address displays the new URL address of the jump.

For example, the following:

Rewrite ^ / (.*) http://www.baidu.com/$1 permanent

Description:

Rewrite is a fixed keyword, which means that the rewrite matching rule is started.

Regex is ^ / (. *). This is a regular expression that matches the complete domain name and the following path address.

Replacement is the http://www.baidu.com/$1 piece, of which $1 is taken from the regex section (). The URL to jump to if the match is successful.

Flag is permanent, which stands for permanent redirection, that is, to jump to an http://www.baidu.com/$1 address.

Let's do a simple demo to simulate:

1. There is an app.js under our test project. The code is as follows:

Const Koa = require ('koa'); const app = new Koa (); const router = require (' koa-router') (); / / add routing router.get ('/', ctx = > {ctx.body = 'Welcome to index page Page';}); router.get ('/ home', ctx = > {ctx.body = 'Welcome to home Page';}); router.get ('/ 404, ctx = > {ctx.body = '404.'}) / / load routing middleware app.use (router.routes ()); app.listen (3001, () = > {console.log ('server is running at http://localhost:3001');});)

Then after running node app.js on the command line, we can access http://localhost:3001 in the browser and access our corresponding page. But now I want to deploy the node project to my local nginx server. For nginx installation, please see my article and then I want to use the domain name to access our project, so we need to configure it in our nginx.conf:

Cd / usr/local/etc/nginx

Then use the command: sudo open / usr/local/etc/nginx/nginx.conf-a 'sublime text' command to open the nginx.conf configuration as follows:

Worker_processes 1 leading events {worker_connections 1024;} http {include mime.types; default_type application/octet-stream; sendfile on; # tcp_nopush on; # keepalive_timeout 0; keepalive_timeout 65; # gzip on; server {listen 8081; server_name localhost; location / {root html; index index.html index.htm;} error_page 500 502 503 504 / 50x.hml; location = / 50x.html {root html }} server {listen 8088; server_name xxx.abc.com; location / {proxy_pass http://127.0.0.1:3001; rewrite ^ / (. *) http://www.baidu.com permanent;}

As in the above code, I listen that the port number is 8088, and then the server_name configuration is set to xxx.abc.com. Then when we visit http://xxx.abc.com:8088/, we will first reverse proxy to the corresponding page of node under our http://127.0.0.1:3001. After the reverse proxy is completed, we will use rewrite to redirect the Baidu page. After the above configuration is completed, we need to restart the nginx server; use the command:

Then when we visit http://xxx.abc.com:8088/ in the browser, we will execute the following figure. It will redirect the http://xxx.abc.com:8088/ permanently, then visit Baidu, temporarily redirect to the Baidu page, and finally load the address of the Baidu page, as shown in the following demonstration:

But if I change permanent to redirect, such as nginx configuration: rewrite ^ / (. *) http://www.baidu.com redirect;, it will become a 302 temporary redirect. As follows:

Three: understand the if instruction

This instruction is used to support conditional judgment, and the configuration of different nginx is selected according to the result of conditional judgment. We can configure the instruction in the server block or location block. Its syntax structure is as follows:

If (condition) {/ /....}

Condition is the meaning of a Boolean true/false.

The global variables available for the Rewrite directive are as follows:

1. $args: this variable stores the request instruction in the request URL. For example, in http://127.0.0.1:3001?arg1=value1&arg2=value2

"arg1=value1&arg2=value2".

2. $content_length: the Content-length field in the request header is stored in this variable.

3. $content_type: the Content-type field in the request header is stored in this variable.

4. $document_root: this variable stores the root path for the current request.

5. $document_uri: this variable stores the current URI of the request, but does not include the request instruction. Like http://xxx.abc.com/home/1?arg1=value1&.

"/ home/1" in arg2=value2;

6. $host: the variable stores some fields of the host in the requested URL, such as xxx.abc.com in http://xxx.abc.com:8080/home.

7. $http_host: the only difference between this variable and $host is with the port number: for example, the one above is xxx.abc.com:8080

8. $http_user_agent: the client's agent information is stored in the variable.

9. $http_cookie, which stores the client's cookie information.

10. $remote_addr the address where the client is stored in this variable.

11. $remote_port this variable stores the port number for the client to establish a connection with the server.

12. The user name of the client is stored in the $remote_user variable.

13. The name of the local file resource sent to the backend server is stored in the $request_body_file variable

14. The $request_method variable stores the client request method, such as' GET', 'POST', and so on.

15. The $request_filename variable holds the pathname of the currently requested resource file.

16. The $request_uri variable stores the URI of the current request with the request instruction.

17. $query_string has the same meaning as the variable $args.

18. The $scheme variable stores the protocol used by the client request, such as' http', 'https', etc.

19. The $server_protocol variable stores the version of the client request protocol, such as' HTTP/1.0', 'HTTP/1.1', and so on.

. Wait

The basic syntax of regular expressions:

1. Match variables

'~' indicates that the matching process is case-sensitive.

'~ *' indicates that the matching process is not case-sensitive.

If the'~ 'match fails, then the condition is true.

If the'! ~ * 'match fails, then the condition is true.

For example, as follows:

Meaning of if ($http_user_agent ~ MSIE) {/ / Code: whether the $http_user_agent value contains a MSIE string, and if it is true, otherwise it is false}

two。 Determine whether the requested file exists

If the requested file exists, the condition is true.

'!-f' returns true if the directory of the file exists and the file does not exist. False if neither the file nor the directory exists.

If the requested directory does not exist, the requested file exists, which is also false.

If (- f $request_filename) {/ / determine whether the requested file exists} if (!-f $request_filename) {/ / determine whether the requested file does not exist}

3. Determine whether the requested directory uses'- d' and'!-d'

Using'- dwells, true is returned if the requested directory exists. Otherwise, false is returned.

Using'!-dcards, true is returned if the requested directory does not exist, but the requested parent directory does. If the parent directory does not exist, return false.... And so on some other grammars, not much introduction.

Now let's use the if instruction to add some judgment to nginx. For example, when we visit http://xxx.abc.com:8080/home, if $host = 'xxx.abc.com', redirect is done. The nginx configuration code is as follows:

Server {listen 8088; server_name xxx.abc.com; location / {proxy_pass http://127.0.0.1:3001; if ($host = 'xxx.abc.com') {rewrite ^ / (. *) http://www.cnblogs.com redirect;}

Nginx is configured so that if we visit http://xxx.abc.com:8088, it will be redirected to http://www.cnblogs.com.

For example, more judgments, such as if the user agent is accessed by mobile phone, jump directly to a page, you can also use if judgment. For example, as follows:

If ($http_user_agent * "(Android) | (iPhone) | (Mobile) | (WAP) | (UCWEB)") {rewrite ^ / $http://www.cnblogs.com permanent;}

4: understand hotlink protection and nginx configuration

What is hotlink protection? Hotlink theft can understand pirate image links, that is, stealing other people's pictures and using them on their own servers, then hotlink protection can be understood as preventing others from stealing my pictures.

The implementation principle of hotlink protection: when the client requests resources from the server, in order to reduce the network bandwidth and improve the response time, the server will not send all the resources back to the client at once. For example, when requesting a web page, the text content of the web page will be sent back first. when the client browser finds that there is a picture in the process of parsing the text, it will launch a request for the image resource to the server again. the server sends the stored image resources to the client. But if this picture is linked to a server on another site, for example, in my project, I quoted a picture from Taobao, then when our website reloads, we will request Taobao's server. Then this is likely to cause a burden on Taobao server. So this is chain theft. So we need to achieve hotlink protection.

Hotlink protection: use the Referer header field of the request header in the http protocol to determine the source address of the currently visited web page or file. With the value of the header field, we can detect the source address that accesses the target resource. If the destination source address is not the URL in our own site, then in this case, we take preventive measures to achieve hotlink protection. But note that the values in the Referer header field can be changed. Therefore, this method can not completely safely stop hotlink protection.

Use the Rewrite function of the Nginx server to achieve hotlink protection.

There is an instruction valid_referers in Nginx. This directive can be used to get a value in the Referer header field and assign a value to the Nginx global variable $invalid_referer based on that value. If there is no value in the Referer header field that matches the valid_referers directive, the $invalid_referer variable will be assigned a value of 1. 0.

The basic syntax of the valid_referers directive is as follows:

Valid_referers none | blocked | server_names | string

None: detects a situation where the Referer header domain does not exist.

Blocked: detect if the value of the Referer header domain is deleted or camouflaged by a firewall or proxy server. In this case, the value of the header field does not start with "http://" or" https://".

Server_names: sets one or more URL to detect whether the value of the Referer header field is one of the URL.

So if we have the valid_referers instruction and the $invalid_referer variable, we can use the Rewrite function to achieve hotlink protection.

Let's introduce two scenarios: first, according to the type of resource requested. Second: according to the request directory.

1. The hotlink protection configuration based on the request file type is listed below:

Server {listen 8080; server_name xxx.abc.com location ~ * ^. +\. (gif | jpg | png | swf | flv | zip) ${valid_referers none blocked www.xxx.com www.yyy.com * .baidu.com * .tabobao.com; if ($invalid_referer) {rewrite ^ / http://www.xxx.com/images/forbidden.png;}

As the basic configuration above, when a network connection initiates a request for a picture resource with the suffix of gif, jpg or png, when there is a media resource with the suffix of swf or flv, or a compressed resource with the suffix of rar or zip, if it is detected that the Referer header domain does not comply with the valid_referers directive, then it is not a resource request of this site.

Location ~ * ^. +\. (gif | jpg | png | swf | flv | rar | zip) $this configuration means to set the file type of hotlink protection.

Valid_referers none blocked www.xxx.com www.yyy.com * .baidu.com * .tabobao.com; can be understood as whitelist, which allows the whitelist of domain names to be linked by files. If the requested resource file does not start with these domain names, it means that the requested resource file is not a request under this domain, so it can be judged to be a hotlink. So if it is not a request in this domain, you will use Rewrite to redirect to the http://www.xxx.com/images/forbidden.jpg image, such as if the image is an x or other logo, and then other websites will not be able to access your image.

two。 The configuration of hotlink protection based on the request directory is listed below:

Server {listen 8080; server_name xxx.abc.com location / file/ {root / server/file/; valid_referers none blocked www.xxx.com www.yyy.com *. Baidu.com * .tabobao.com; if ($invalid_referer) {rewrite ^ / http://www.xxx.com/images/forbidden.png;}

So far, this is the end of this article on the detailed explanation of the redirect configuration and practice of Rewrite in Nginx. For more information about Nginx Rewrite redirection, please search for previous articles or continue to browse the relevant articles below. I hope you will support it in the future!

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