Nginx rewrite rules (2)
Requirements: research and development put forward some routing jump requirements.
Problem solving: when special circumstances, business and R & D can not be dealt with quickly, operators need to jump quickly to solve temporary problems and avoid larger bug.
Case 1:
Temporarily forward the request for path / colorv1/getcolorv1 to v2 with the parameters after the question mark:
Location ~ ^ / (.) / colorv1/getcolorv1 ${
Proxy_pass http://category-color-api/$1/$2/colorv2/getcolorv2?$args;
}
Case 2:
Uri with any beginning and end, redirect to "http://test.jenkins.com/jenkins""
Location / {rewrite ^ / (. *) $http://test.jenkins.com/jenkins;}
Location / jenkins {
Proxy_pass http://127.0.0.1:8080/jenkins;
Proxy_set_header Host $host
Proxy_set_header X-Real-IP $remote_addr
Proxy_set_header X-Forwarded_For $proxy_add_x_forwarded_for
}
Case three
If the accessed URL ends with .sh .bash, the status code 403 is returned.
Location. *. (sh | bash)? ${
Return 403
}
Case four
How to implement the nginx multi-judgment conditional statement? For example, a request that meets two conditions at the same time is forwarded.
The logic of the if condition does not support the operation of & & or | in the configuration of nginx, and the nested syntax of if is not supported.
Otherwise, an error will be reported: nginx: [emerg] invalid condition; we can implement this as a variable.
For example, to request access to / color, the request method is post, and refer returns 200 for abc.com;: and displays the content {"code": 1, "msg": "published successfully"}. Other requests that do not meet these two conditions are forwarded to gateway.
Location ~ / color$ {set $post 0; # # define variable if ($request_method ~ * "POST") {set $post "${post} 1";} if ($http_referer ~ * "abc.com") {set $post "${post} 2" } if ($post = "012") {return 200'{"code": 1, "msg": "release successful"}';} proxy_pass http://$gateway/a-b-api$request_uri;} case 5
Forbid tools such as Scrapy and UA from fetching empty
If ($http_user_agent ~ * (Scrapy | Curl | HttpClient | ^ $)) {return 403;}
Attachment: after the nginx configuration is completed, the common verification methods of curl
When we have made some conditional restrictions, we can only go online if we pass the local curl verification:
-H "referer:abc" / / set referer
-A "okhttp/3.12.0" / / set request http_user_agent
-X POST / / request method post
-d'{}'/ / request parameters
Curl-H "referer:"-A "okhttp/3.12.0"-X POST-d'{"user": "admin", "passwd": "12345678"} 'http://test.abc.com/1/7.3/color?client=064bfc8ch577e5f6