Nginx Rewrite Rules, nginxrewrite Rewrite

Source: Internet
Author: User
Tags to domain

Nginx Rewrite Rules, nginxrewrite Rewrite

The main function of Rewrite is to rewrite the URL. The Rewrite function of Nginx is to use the global variables provided by nginx or the variables set by itself, and implement url rewriting and redirection using the regular expression and flag. This article describes the rewrite rules that are often used in actual projects.

The rewrite function of Nginx requires the support of PCRE software, that is, regular expression statements compatible with perl are used for rule matching. Nginx will support the rewrite module by default parameter compilation, but it must also support PCRE. For Nginx installation, refer to this article: CentOS7 use source code compilation to install Nginx.

Rewrite is a key command for URL rewriting. Based on the regex (Regular Expression) content, it is redirected to replacement, ending with a flag.

Nginx rewrite command execution sequence

1. Execute the rewrite command of the server block (the block here refers to the area surrounded by {} after the server keyword, And the other xx blocks are similar)

2. Execute location matching

3. Execute the rewrite command in the selected location

If the URI of a specific step is overwritten, execute 1-3 again until an existing file is found.

If the number of cycles exceeds 10, the Error 500 Internal Server Error is returned.

Flag

The rewrite syntax is very simple, such:

rewrite regex URL [flag];

Rewrite is a keyword, regex is a regular expression, URL is the content to replace, and [flag] is a tag bit. It has the following values:

Last: equivalent to the [L] Mark of Apache, indicating that rewrite is completed.

Break: stops executing subsequent rewrite instruction sets for the current VM.

Redirect: 302 temporary redirection is returned. The address bar displays the redirected address.

Permanent: 301 permanent redirection is returned. The address bar displays the redirected address.

Because 301 and 302 cannot simply return the status code and must have a redirected URL, which is why the return command cannot return 301,302. Here, the difference between last and break is a bit difficult to understand:

Last is generally written in server and if, while break is generally used in location.

Last does not terminate url matching after rewriting, that is, the new url will go through the matching process again from the server, and the break will terminate the matching after rewriting.

Both break and last can execute subsequent rewrite commands.

Let's look at a simple example:

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

In the first rewrite rule, we can use a friendly URL: Signature.

In the second rule.

If command and global variable

The if command syntax is if (condition) {...}, which is used to determine the given condition. If true, the rewrite command in braces is executed.

Let's look at the Code rules:

If ($ http_user_agent ~ MSIE) {rewrite ^ (. *) $/msie/$1 break;} // if the UA contains "MSIE", rewrite requests to the/msid/directory if ($ http_cookie ~ * "Id = ([^;] +) (:;| $)") {set $ id $1 ;}// if the cookie matches the regular expression, if ($ request_method = POST) {return 405;} // if the submission Method is POST, status 405 (Method not allowed) is returned ). Return cannot return 301,302 if ($ slow) {limit_rate 10 k;} // speed limit. $ slow can set if (! -F $ request_filename) {break; proxy_pass http: // 127.0.0.1;} // reverse proxy to localhost if the requested file name does not exist. Here, the break also stops the rewrite check if ($ args ~ Post = 140) {rewrite ^ http://mysite.com/permanent;} // If the query string contains "post = 140", permanently redirect to mysite.com

Global variables can be used in the if command:

$ Args: # This variable is equal to the parameter in the request line, which is 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 by the current request in the root command.

$ Host: The Request host header field. Otherwise, it is 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: IP address of the client.

$ Remote_port: the port of the client.

$ Remote_user: User name verified by Auth Basic Module.

$ Request_filename: the file path of the current request, which is generated by the root or alias command and URI request.

$ Scheme: HTTP protocol (such as http and https ).

$ Server_protocol: the protocol used by the request, usually HTTP/1.0 or HTTP/1.1.

$ Server_addr: the server address. This value can be determined after a system call is completed.

$ Server_name: server name.

$ Server_port: the port number of the request to reach the server.

$ Request_uri: the original URI that contains the request parameters, excluding the host name, for example, "/foo/bar. phparg = baz ".

$ Uri: The current URI without request parameters. $ uri does not contain the host name, for example, "/foo/bar.html ".

$ Document_uri: Same as $ uri.

Use return to redirect

We sometimes need to use rewrite on Nginx for 301 address redirection, such as the following rules:

rewrite ^ $scheme://www.mysite.com$request_uri permanent;

When any url is accessed, 301 is permanently directed to the url of www.mysite.com. This statement is correct, but the rewrite regular expression will consume some resources because it is not recommended on the official nginx website. We can also use return to achieve 301 jump, which is simple and practical. Let's look at the instance:

301 permanent orientation to new domain name

server {    listen 80;    listen 443 ssl;    server_name www.old-name.com old-name.com;    return 301 $scheme://www.new-name.com;}

The above code redirects the old domain name 301 to the new domain name. If the website wants to change the new domain name, use this method to perform the 301 redirect.

Jump to domain name with www without www 301

server {    listen 80;    listen 443 ssl;    server_name mysite.com;    return 301 $scheme://www.mysite.com$request_uri;}

Http site 301 jump to https site

server {    listen 80;    server_name www.mysite.com;    return 301 https://www.mysite.com$request_uri;}

The above is an introduction to rewrite and redirection of Nginx. If it is useful, Please practice it multiple times.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.