[Reprint] Nginx Rewrite Rules Guide

Nginx Rewrite Rules Guide

https://linux.cn/article-5229-1.html

 

Author:  Mo North 

| 2015-04-09 09:54 Comments:  1  Favorite:  10    

When the operation and maintenance experience to be rewritten, the programmers tend to write after the rewrite rules, to you, and then you configure the production environment. For the final analysis, regular rewrite rules match, how can we do the operation and maintenance of a regular expression do not understand? At least the most basic regular expressions and write. Ali quote a word (a user said Ali said, is not clear in the end is not from Ali) "do not understand the operation and maintenance procedures, not luck dimension; do not understand the development of operation and maintenance, is not a good development.". Regular expressions is a language of Kazakhstan. When you learn a language, you will inevitably encounter the language of regular expressions this chapter. Here I recommend a very good regular expressions book that contains common language of regular wording such as sed, perl, bash, awk, php, c #, java, javascript, python, ruby ​​and so on, "Regular Expressions Cookbook, 2nd Edition "there are Chinese version, we can look to the network.

This article describes the nginx rewrite module, create rewrite rules wizard, fast and easy to create a new right rewrite rules, not to help people. Meanwhile, if you want to convert apache Nginx, the rewrite rules are to be changed slightly.

A. Rewrite module Introduction

nginx rewrite module is a simple regular expression match in combination with a virtual stack machine. It depends on the PCRE library, so you need to install pcre. The redirection and related variables to select a different configuration from one location to jump to another location, but this may be performed up to 10 cycles, more than 500 nginx returns an error. At the same time, rewrite module contains the set of instructions to create a new variable and set its value, which is useful in some situations, such as recording conditions identification, pass parameters to another location, recording what has been done and so on.

Two. Rewrite instruction module

break

Syntax: break

Default: none

Using field: server, location, if

Completion of the current set of rewrite rules, stop the execution of other rewrite rules.

if

Syntax: if (condition) {...}

Default: none

Using field: server, location

Note: Try to consider using try_files instead. Determination condition may have the following values:

  1. The name of a variable: null character biography "" or some "0" beginning of the string is false.
  2. String Comparison: Use operator = or =!
  3. Regular expression match: ~ (case sensitive) and ~ * (case insensitive), and the negation operator ~ * ~!!.
  4. If a file exists: using the -f and -f operator!
  5. Directory exists: Use the -d and -d operators!
  6. Files, directories, symbolic link exists: using the -e -e and operator!
  7. If the file is executable: Use -x and -x operator!

return

Syntax: return code

Default: none

Using field: server, location, if

Stop processing and return a status code to the client. Non-standard status code 444 will close the connection, it does not send any response header. Status code can be used are: 204,400,402-406,408,410, 411, 413, 416 and 500-504. If the status code accompanying text paragraph, the text will be placed in the body in response. Conversely, if the status code is behind a URL, which will be the first location complement value. No state codes URL will be treated as a 302 status code.

rewrite

语法:rewrite regex replacement flag

Default: none

Using field: server, location, if

In accordance with the regular expression associated with the string to modify URI, an instruction execution order of appearance in the configuration file. Rewrite instruction tag may be added later.

Note: If the replacement string with http: //, the request will be redirected, and no excess rewrite instruction execution.

Tail marks (In Flag) may be the following values:

  • last - stop instruction module rewriting processing, after searching URI matches the location and changes.
  • break - complete rewrite instruction.
  • redirect - returns 302 temporary redirect, if you replace the field with the http: // at the beginning were using.
  • permanent - returns 301 permanent redirect.

rewrite_log

Syntax: rewrite_log on | off

Default value: rewrite_log off

Using field: server, location, if

Variables: None

The record level of rewriting notice the log in the error log when enabled.

set

Syntax: set variable value

Default: none

Using field: server, location, if

Setting a specific value for the given variable.

uninitialized_variable_warn

语法:uninitialized_variable_warn on|off

Default value: uninitialized_variable_warn on

Using field: http, server, location, if

Controls whether recorded warnings of uninitialized variables.

III. Rewrite Rules part

3.1 Any of the first part of the rewrite rule is a regular expression

Parentheses may be used to capture subsequent reference can be based on the position, the variable value depending on the position captured in the order of regular expressions, $ 1 a reference value of the first brackets, a reference value of $ 2 in the second bracket, thus analogy. Such as:

  1. ^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$

$ 1 is the string two lowercase letters, $ 2 is a string of lower case letters and numbers 0 to 9 consisting of five characters, $ 3 will be a file name, $ 4 png, jpg, wherein a gif of.

The second part of the URI rewrite rules 3.2

Request to be rewritten. The URI may contain regular expressions to capture the positional parameters or the nginx configuration variables at any level. Such as:

  1. /data?file=$3.$4

If the URI does not match any location nginx configuration, it will then return to the client 301 (permanent redirect) or 302 (temporary redirect) status code to indicate the type of redirection. The status code can be explicitly specified by the third argument.

The third rewrite rule section 3.3

The third part is a tail mark (flag). last tag will result in the rewritten search URI matches other location nginx of up to 10 cycles. Such as:

  1. rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /data?file=$3.$4 last;

The instructions may itself as a break instruction. Such as:

  1. if ($bwhog) {
  2. limit_rate 300k;
  3. break;
  4. }

Another module rewriting processing instruction is stopped return, to the main control module for processing HTTP requests. This means that, nginx returns information directly to the client, in conjunction with the client presents error_page formatted HTML page or activate different modules to fulfill the request. If the status code accompanying text paragraph, the text will be placed in the body in response. Conversely, if the status code is behind a URL, which will be the first location complement value. No state codes URL will be treated as a 302 status code. Such as:

  1. location = /image404.html {
  2. return 404 "image not found\n";
  3. }

IV.  Examples

  1. http {
  2. # 定义image日志格式
  3. log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status;
  4. # 开启重写日志
  5. rewrite_log on;
  6. server {
  7. root /home/www;
  8. location / {
  9. # 重写规则信息
  10. error_log logs/rewrite.log notice;
  11. # 注意这里要用‘’单引号引起来,避免{}
  12. rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /data?file=$3.$4;
  13. # 注意不能在上面这条规则后面加上“last”参数,否则下面的set指令不会执行
  14. set $image_file $3;
  15. set $image_type $4;
  16. }
  17. location /data {
  18. # 指定针对图片的日志格式,来分析图片类型和大小
  19. access_log logs/images.log main;
  20. root /data/images;
  21. # 应用前面定义的变量。判断首先文件在不在,不在再判断目录在不在,如果还不在就跳转到最后一个url
  22. try_files /$arg_file /image404.html;
  23. }
  24. location = /image404.html {
  25. # 图片不存在返回特定的信息
  26. return 404 "image not found\n";
  27. }
  28. }

V.  Create a new rule again

Upon receipt To create a new rewrite rules to figure out what the demand is, and then decide how to do it. After all, the consumption of resources has also rewritten the efficiency of the points. Some of these questions below to help:

  1. Your URL pattern is what?
  2. Is there more than one way to achieve?
  3. Whether you need to capture part of the URL as a variable?
  4. Redirected to another web you can see my rules?
  5. Do you want to replace the query string parameters?

Check the Web site or application layout, clear URL pattern. Long-winded one: I emphasize again and again, operation and maintenance can not be divorced from the development, operation and maintenance to be involved in development. If there is more than one way to achieve, to create a permanent redirect. At the same time, rewrite the definition of a specification to enable clean URLs, it can also help site easier to find.

Example 1. To the surface redirected to the home home directory, the directory structure is as follows:

  1. /
  2. /home
  3. /home/
  4. /home/index
  5. /home/index/
  6. /index
  7. /index.php
  8. /index.php/

Rewrite rules are as follows:

  1. rewrite ^/(home(/index)?|index(\.php)?)/?$ $scheme:
  2. //$host/ permanent;

$ Scheme and specify the $ host variable, because to do a permanent redirect and want nginx to use the same parameters to construct URL.

Example 2. To each portion are recorded URL, a regular expression can be used to capture the URI, then assigned to the variable specified position variable, see example above.

Example 3. When the result in an internal redirect or rewrite rule indicating the location the client calls itself defined rule, special action must be taken to avoid overwrite cycles. Such as: the server configuration section defines a rule last band flag, in reference LOCATION, must break flag.

  1. server {
  2. rewrite ^(/images)/(.*)\.(png|jpg|gif)$ $1/$3/$2.$3 last;
  3. location /images/ {
  4. rewrite ^(/images)/(.*)\.(png|jpg|gif)$ $1/$3/$2.$3 break;
  5. }
  6. }

4. Examples of rewrite rules as part of the new query string parameter passed is one of the objectives of using rewrite rules. Such as:

  1. rewrite ^/images/(.*)_(\d+)x(\d+)\.(png|jpg|gif)$ /resizer/$1.$4?width=$2&height=$3? last;

nginx rewrite rules say it quite simple than done, with emphasis on regular expressions, it is also necessary to consider the nginx execution order.  

Guess you like

Origin www.cnblogs.com/jinanxiaolaohu/p/12084706.html