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

Detailed explanation of commonly used nginx rewrite rewriting rules

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

Share

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

This article provides some common rewrite rewriting rules to beautify links to web pages. If you don't know how to get the $1 $2 in the rule, just remember that the $1 in the first () and the $2 in the second ().

The requested URL is for people, and the rewritten URL is for computers.

Perform a search

The purpose of this rule is to perform a search for keywords contained in the URL.

Requested URL / / hqidi.com/search/some-search-keywords

URL / / hqidi.com/search.php?p=some-search-keywords after rewriting

Rewrite the rule rewrite ^ / search/ (. *) $/ search.php?p=$1?

User profile page

Most dynamic websites that run visitor registration provide a page where you can view your profile. The URL of this page contains the user's UID and user name.

Requested URL / / hqidi.com/user/47/dige

URL / / hqidi.com/user.php?id=47&name=dige after rewriting

Rewrite the rule rewrite ^ / user/ ([0-9] +) / (. +) $/ user.php?id=$1&name=$2?

Multiple parameters

Some websites use different syntax for string parameters, such as separating unnamed parameters with a slash "/"

Requested URL / / hqidi.com/index.php/param1/param2/param3

URL / / hqidi.com/index.php?p1=param1&p2=param2&p3=param3 after rewriting

Rewrite the rule rewrite ^ / index.php/ (. *) $/ index.php?p1=$1&p2=$2&p3=$3?

An encyclopedia-like format

This format features a prefix directory followed by the name of the article

Requested URL / / hqidi.com/wiki/some-keywords

URL / / hqidi.com/wiki/index.php?title=some-keywords after rewriting

Rewrite the rule rewrite ^ / wiki/ (. *) $/ wiki/index.php?title=$1?

Forum

Forums generally use two parameters, one topic identification (topic) and one starting point (starting post).

Requested URL / / hqidi.com/topic-1234-50-some-keywords.html

URL / / hqidi.com/viewtopic.php?topic=1234&start=50 after rewriting

Rewrite the rule rewrite ^ / topic- ([0-9] +)-([0-9] +)-(. *)\ .html$ viewtopic.php?topic=$1&start=$2?

Articles on the new website

The feature of this URL structure consists of an article identifier, followed by a slash, and a list of keywords.

Requested URL / / hqidi.com/88/future

URL / / hqidi.com/atricle.php?id=88 after rewriting

Rewrite the rule rewrite ^ / ([0-9] +) /. * $/ aticle.php?id=$1?

The last question mark

If the replaced URI contains parameters (such as URI like / app/test.php?id=5), the parameters are automatically appended to the replacement string by default, by adding? at the end of the replacement string. Tag to solve this problem.

Rewrite ^ / users/ (. *) $/ show?user=$1? Last

Compare one plus? Marked or not? Marked URL jump difference:

Rewrite ^ / test (. *) $/ / hqidi.com/home premanent

The URL address of access / / hqidi.com/test?id=5 after 301 jump is / / hqidi.com/home?id=5

Rewrite ^ / test (. *) $/ / hqidi.com/home? Premanent

The URL address of access / / hqidi.com/test?id=5 after 301 jump is / / hqidi.com/home

The rewrite function of Nginx needs the support of PCRE software, that is, rule matching is carried out through perl compatible regular expression statements. Compiling nginx with default parameters will support rewrite's module, but it must also be supported by PCRE

Rewrite is the key instruction to implement URL rewriting. According to the regex (regular expression) part of the content, it is redirected to replacement, ending with a flag tag.

Nginx rewrite instruction execution sequence

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

two。 Perform location matching

3. Execute the rewrite instruction in the selected location

If one of the steps URI is rewritten, cycle through 1-3 until a real file is found.

If there are more than 10 loops, a 500 Internal Server Error error is returned.

Flag marker bit

The syntax of rewrite is simple, such as:

Rewrite regex URL [flag]

Rewrite is the keyword, regex is the regular expression, URL is the content to replace, and [flag] is the meaning of the tag bit, which has the following values:

Last: equivalent to the [L] tag of Apache, indicating completion of rewritebreak: stop executing the subsequent rewrite instruction set of the current virtual host redirect: return 302 temporary redirection, the address bar will display the jump address permanent: return 301 permanent redirection, the address bar will display the jump address

Because 301 and 302 cannot simply return the status code, they must also have a redirected URL, which is why the return instruction cannot return 301302. Here the difference between last and break is a little hard to understand:

Last is generally written in server and if, while break generally uses url matching after last without terminating rewriting in location, that is, the new url will go through the matching process from server again, while both break and last after break termination rewriting can organize and continue to execute the following rewrite instructions.

Let's look at a simple example:

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

In the first rewriting rule, we can use the friendly URL: http://mysite.com/listings/123 instead of http://mysite.com/listing.html?listing=123, which means that after we type http://mysite.com/listings/123 in the browser's address bar, the actual URL resource accessed is http://mysite.com/listing.html?listing=123.

In the second rule, requests for files such as http://mysite.com/images/bla_500x400.jpg are rewritten to the http://mysite.com/resizer/bla.jpg?width=500&height=400 address and continue to try to match the location.

If directive and global variable

The syntax of the if instruction is if (condition) {...}, which determines the given conditional condition. If true, the rewrite instruction in curly braces is executed.

Take a look at the code rules:

If ($http_user_agent ~ MSIE) {rewrite ^ (. *) $/ msie/$1 break;} / / if UA contains "MSIE", rewrite requests to if ($http_cookie ~ * "id= ([^;] +) (?; | $)") {set $id $1;} / if cookie matches regular, set variable $id equal to regular reference part if ($request_method = POST) {return 405 } / / if the submit method is POST, status 405 (Method not allowed) is returned. Return cannot return 301302 if ($slow) {limit_rate 10k;} / / speed limit, and $slow can set if (!-f $request_filename) {break; proxy_pass http://127.0.0.1;} / / if the requested file name does not exist, reverse proxy to localhost. The break here 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

In the if directive, you can use global variables, such as:

$args: # this variable is equal to the parameter in the request line, the same as the $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: HTTP protocol (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 containing 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.

Use return to jump

We sometimes need to use rewrite to jump 301 addresses on Nginx, such as the following rules:

Rewrite ^ $scheme://www.mysite.com$request_uri permanent

When visiting any url, 301 will be permanently directed to www.mysite.com 's url. This is correct, but because of the use of rewrite regular matching, it will waste some resources, which is not recommended on the official website of nginx. We can also use return to achieve 301jump, which is simple and practical. See the example:

301 is permanently directed to a 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 realizes the old domain name 301 jump to the new domain name, if the website wants to change the new domain name, then use this method to do 301 jump.

Jump from domain name 301 without www to domain name with www

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

Http site 301 jumps to https site

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

The above is the introduction to rewrite rewriting and redirection of Nginx. If you think it is useful, please practice it many times and keep this article in order not to get lost. I also hope that you will give us more support.

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