Nginx Config URL rewrite

Source: Internet
Author: User

URL rewriting refers to a rule, such as common pseudo-static, 301 redirection, browser orientation, and so on, by configuring the Conf file to have a certain state in the URL of the site.

Rewrite syntax

Write in the block of the configuration file server , such as:

server {    rewrite 规则 定向路径 重写类型;}
    • Rule: can be a string or a regular to indicate the destination URL that you want to match
    • Directed path: Indicates the path to be directed after matching to the rule, and can be used $index to represent capturing groupings in the regular rule if there are regular rules
    • Rewrite type:
      • Last: Equivalent to Apache Reed (L) mark, indicating completion rewrite, browser address bar URL address unchanged
      • break; After the rule match is complete, the match is terminated, no longer matches the following rule, the URL address of the browser address bar is not changed
      • Redirect: Returns 302 temporary redirect, the browser address will show the URL address after the jump
      • Permanent: Return 301 Permanent Redirect, the browser address bar will show the URL address after the jump
Simple example
server {    # 访问 /last.html 的时候,页面内容重写到 /index.html 中    rewrite /last.html /index.html last;    # 访问 /break.html 的时候,页面内容重写到 /index.html 中,并停止后续的匹配    rewrite /break.html /index.html break;    # 访问 /redirect.html 的时候,页面直接302定向到 /index.html中    rewrite /redirect.html /index.html redirect;    # 访问 /permanent.html 的时候,页面直接301定向到 /index.html中    rewrite /permanent.html /index.html permanent;    # 把 /html/*.html => /post/*.html ,301定向    rewrite ^/html/(.+?).html$ /post/$1.html permanent;    # 把 /search/key => /search.html?keyword=key    rewrite ^/search\/([^\/]+?)(\/|$) /search.html?keyword=$1 permanent;}
The difference between last and break

Because 301 and 302 cannot simply return a status code, there must also be a redirected URL, which is why the return instruction cannot return 301,302. Here the last and break differences are a bit difficult to understand:

    • Last is generally written in server and if, and break is generally used in location
    • Last does not terminate the rewritten URL match, that is, the new URL will go through the matching process again from the server, and break terminates the rewritten match
    • Both break and last can organize the continuation of the subsequent rewrite instructions.

locationonce returned break , it takes effect directly and stops subsequent matches.location

server {    location / {        rewrite /last/ /q.html last;        rewrite /break/ /q.html break;    }    location = /q.html {        return 400;    }}
    • The access /last/ is rewritten to /q.html , and then a new re-match is used uri , exactly matching to locatoin = /q.html and then returning the400
    • /breakwhen accessed /q.html , it is stopped directly because it returned. break
If judgment

Just the simple rewrite above is often not enough to meet the requirements, such as the need to determine when the file does not exist, when the path contains XX conditions, you need to useif

Grammar
if (表达式) {}
    • When an expression is just a variable, if the value is empty or any string starting with 0 is treated as false
    • When you directly compare variables and content, use = or! =
    • ~ Regular expression Match, ~* case-insensitive match,!~ case-sensitive mismatch

Some built-in conditions to judge:

    • -F and!-f to determine if a file exists
    • -D and!-d to determine if a directory exists
    • -E and!-e to determine if a file or directory exists
    • -X and!-x to determine if a file is executable
Built-in global variables
$args: This variable equals the parameter in the request line, with 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 instruction of the current request.$host: Requests the Host header field, otherwise 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: The IP address of the client.$remote _port: The port of the client.$remote _user: The user name that has been validated by the 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 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, this value can be determined after a system call is completed.  $server _name: server name.  $server _port: The port number on which the request reached the server.  $request _uri: The original URI containing the request parameters, not including the hostname, such as: "/foo/bar.php?arg= Baz ".  $uri: The current URI without the request parameter, $uri does not contain a hostname, such as "/foo/bar.html".  $document _uri: Same as $uri.  

Such as:

访问链接是:http://localhost:88/test1/test2/test.php 网站路径是:/var/www/html$host:localhost$server_port:88$request_uri:http://localhost:88/test1/test2/test.php$document_uri:/test1/test2/test.php$document_root:/var/www/html$request_filename:/var/www/html/test1/test2/test.php
Example
# 如果文件不存在则返回400if (!-f $request_filename) {    return 400;}# 如果host不是xuexb.com,则301到xuexb.com中if ( $host != "xuexb.com" ){    rewrite ^/(.*)$ https://xuexb.com/$1 permanent;}# 如果请求类型不是POST则返回405if ($request_method = POST) {    return 405;}# 如果参数中有 a=1 则301到指定域名if ($args ~ a=1) {    rewrite ^ http://example.com/ permanent;}

In a scenario, you can combine location rules to use, such as:

# 访问 /test.html 时location = /test.html {    # 默认值为xiaowu    set $name xiaowu;    # 如果参数中有 name=xx 则使用该值    if ($args ~* name=(\w+?)(&|$)) {        set $name $1;    }    # 301    rewrite ^ /$name.html permanent;}

The above indicates:

    • /test.html =/xiaowu.html
    • /test.html?name=ok =/ok.html?name=ok
Location syntax

serverused in blocks, such as:

server {    location 表达式 {    }}

Location expression type

    • If you write a path directly, match the path of the
    • ~ indicates that a regular match is performed, case-sensitive
    • ~* indicates that a regular match is performed, is case-insensitive
    • ^~ indicates normal character matching. Match with prefix. If the match succeeds, the other location is no longer matched.
    • = Exact Match of ordinary characters. Which is exactly the same.
Priority level
    1. The equals type (=) has the highest precedence. Once the match succeeds, no other matches are found.
    2. An ^~ type expression. Once the match succeeds, no other matches are found.
    3. The priority of the regular expression type (~ ~*). If more than one location has a regular match, the longest regular expression will be used.
    4. The regular string match type. Match by prefix.
Example-Fake address mask true address
server {    # 用 xxoo_admin 来掩饰 admin    location / {        # 使用break拿一旦匹配成功则忽略后续location        rewrite /xxoo_admin /admin break; } # 访问真实地址直接报没权限 location /admin { return 403; }}

Nginx Config URL rewrite

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.