Nginx Rewrite rewrite foundation and instance sharing _nginx

Source: Internet
Author: User
Tags regular expression browser cache domian

Nginx-rewrite regular expression matching

Case matching

~ to match case sensitivity
~* for case-insensitive matching
!~ and!~* are case insensitive and case-insensitive mismatches, respectively.

File and directory matching

-F and!-f are used to determine whether a file exists
-D and!-d used to determine whether a directory exists
-E and!-e used to determine whether a file or directory exists
-X and!-x are used to determine whether a file is executable

Flag Mark

Last equivalent to the [L] tag in Apache, which means complete rewrite
Break termination matches and no longer match the following rule.
REDIRECT Returns 302 the temporary redirect Address bar displays the address after the jump.
Permanent returns 301 the Permanent redirect Address bar displays the address after the jump.


several usages of logcation:

1) Location/{}: Matches any query because all requests start with/. However, regular expression rules are matched by precedence and query.
2) Location =/{}: only match/
3) Location ~* \. (GIF|JPG|JPEG) $


Rewrite \. (gif|jpg) $/logo.png;
}:location is case-insensitive and matches any file that ends with Gif,jpg,jpeg.

Several examples:

Multi-Directory conversion parameters
requirements: ABC.DOMIAN.COM/SORT/2 => abc.domian.com/index.php?act=sort&name=abc&id=2
Rule configuration:

Copy Code code as follows:

if ($host ~* (. *) \.domain\.com) {
Set $sub _name $;
Rewrite ^/sort\/(\d+) \/?$/index.php?act=sort&cid= $sub _name&id=$1 last;
}

Directory Swap
Requirements:/123456/xxxx->/xxxx?id=123456
Rule configuration:
Rewrite ^/(\d+)/(. +)//$2?id=$1 last;

Another automatic rewrite for browser optimization, where the rewrite directory can exist;
For example, set the Nginx to redirect to the/nginx-ie directory in the user's use of IE
The rules are as follows:
Copy Code code as follows:

if ($http _user_agent ~ msie) {
Rewrite ^ (. *) $/nginx-ie/$1 break;
}

Directory automatically add "/", this feature general browser automatic completion

Copy Code code as follows:

if (-D $request _filename) {
Rewrite ^/(. *) ([^/]) $ http://$host/$1$2/permanent;
}

The following may be irrelevant to the generalized rewrite rewrite.

Prohibit htaccess

Copy Code code as follows:

Location ~/\.ht {
Deny all;
}
[Code]
Prohibit multiple directories
[Code]
Location ~ ^/(cron|templates)/{
Deny all; Break
}

A file that starts with a/data is prohibited and can be/data/under a multilevel directory. Log.txt request
Copy Code code as follows:

Location ~ ^/data {
Deny all;
}

Prohibit individual files
Copy Code code as follows:

Location ~/data/sql/data.sql {
Deny all;
}

Set expiration time for Favicon.ico and robots.txt; Here for Favicon.ico 99 days, robots.txt 7 days does not record 404 error log
Copy Code code as follows:

Location ~ (favicon.ico) {
Log_not_found off;
Expires 99d;
Break
}
Location ~ (robots.txt) {
Log_not_found off;
Expires 7d;
Break
}

Sets the browser cache expiration time for a file; This is 600 seconds, and the access log is not logged
Copy Code code as follows:

Location ^~/html/scripts/loadhead_1.js {
Access_log off;
Expires 600;
Break
}

Nginx can also customize the shelf life time of a certain type of file, and specifically look at the following code:
Copy Code code as follows:

Location ~* \. (js|css|jpg|jpeg|gif|png|swf) $ {
if (-f $request _filename) {
Expires 1h;
Break
}
}
The previous code sets the shelf life of the js|css|jpg|jpeg|gif|png|swf file to one hour.

Setting of anti-theft chain:

Anti-Theft chain: If your site is a download site, download the steps should be first through your home page to find the download address to download, in order to prevent some netizens directly access to download the address is not completely through the home page download, we can use the way of anti-theft chain, the specific code is as follows:

Copy Code code as follows:

Location ~* \. (gif|jpg|swf) $ {
Valid_referers none blocked start.igrow.cn sta.igrow.cn;
if ($invalid _referer) {
Rewrite ^/http://$host/logo.png;
}
}

File hotlinking and set expiration time--< hotlinking multiple requests will also open the image of your site Ah, so set the cache time, not every hotlinking request and download this picture >
Copy Code code as follows:

Location ~* ^.+\. (JPG|JPEG|GIF|PNG|SWF|RAR|ZIP|CSS|JS) $ {
Valid_referers None blocked *.jb51.net *.jjonline.com.cn *.lanwei.org *.jjonline.org localhost 42.121.107.189;
if ($invalid _referer) {
Rewrite ^/http://img.jb51.net/forbid.gif;
return 417;
Break
}
Access_log off;
Break
}

Description

The return 417 here is a custom HTTP status code, the default is 403, to conveniently find the correct hotlinking request address via Nginx log files.
"Rewrite ^/http://img.jb51.net/forbid.gif;" Display an anti-theft chain picture
"Access_log off;" Do not log access logs to reduce stress
"Expires 3d" browser cache for all files 3 days


Only fixed IP access to the Web site, and add a password; This is good for authorized applications.

Copy Code code as follows:

Location \ {
Allow 22.27.164.25; #允许的ipd
Deny all;
Auth_basic "KEY"; #认证的一些设置
Auth_basic_user_file htpasswd;
}

Description: The application of location also has a variety of changes, the wording here for the root directory.
Time redirection when files and directories do not exist

Copy Code code as follows:

if (!-e $request _filename) {
#proxy_pass http://127.0.0.1; #这里是跳转到代理ip, there is a listening Web server on this proxy IP
Rewrite ^/http://www.jb51.net/none.html; #跳转到这个网页去
#return 404; #直接返回404码, and then look for the 404.html file specified by root
}

Domain Jump
Copy Code code as follows:

server {
Listen 80;
server_name jump.jb51.net; #需要跳转的多级域名
Index index.html index.htm index.php; #入口索引文件的名字
root/var/www/public_html/; #这个站点的根目录
Rewrite ^/http://www.jb51.net/;
#rewrite到这个地址, functional performance: In the browser input jump.jb51.net and enter, will not have any hint directly into www.jb51.net
Access_log off;
}

Multi-domain Direction
Copy Code code as follows:

server {
Listen 80;

server_name www.jb51.net www.jjonline.org;
Index index.html index.htm index.php;
root/var/www/public_html/;
if ($host ~ "jjonline\.org") {
Rewrite ^ (. *) http://www.jb51.net$1 permanent;
}
}

Level three domain jump
Copy Code code as follows:

if ($http _host ~* "^ (. *) \.i\.jjonline\.cn$") {
Rewrite ^ (. *) http://demo.jb51.net$1;
Break
}

Domain name Mirror to
Copy Code code as follows:

server {
Listen 80;
server_name mirror.jb51.net;
Index index.html index.htm index.php;
root/var/www/public_html;
Rewrite ^/(. *) http://www.jb51.net/$1 last;
Access_log off;
}

A subdirectory is a mirror, here's an example demo subdirectory
Copy Code code as follows:

Location ^~/demo {
Rewrite ^.+ http://demo.jb51.net/last;
Break
}

The following is the rewrite written in the accompanying blog, emlog system rewrite
Copy Code code as follows:

Location ~ {
if (!-e $request _filename) {
Rewrite ^/(. +) $/index.php last;
}
}

Nginx rewrite rewrite rule configuration tutorial

Rewrite can be found in 4 places: ngx_http_srv_conf,ngx_http_sif_conf,ngx_http_loc_conf,ngx_http_lif_conf. correspond to each other:

Ngx_http_srv_conf: Anywhere in the server domain in the configuration file;
Ngx_http_sif_conf: In the If configuration in the server domain in the configuration file;
Ngx_http_loc_conf: Anywhere in the location domain in the configuration file;
Ngx_http_lif_conf: In the If configuration in the location domain in the configuration file;

Example:

Copy Code code as follows:

//...
server {
//...
Rewrite "^/+$"/index.php break;

if ($uri ~* "^/+abc") {
Rewrite "^/+ABC"/abc/index.php break;
}

Location/xy {
Rewrite "^/+xy$"/xy/index.php break;
}
}

The detailed description of location and the powerful features of location can be searched in the search box of this website by typing "ngingx location".
Add
1,break directives
Default value: None; use environment: server,location,if;
The purpose of this instruction is to complete the current rule set and no longer process the rewrite instruction.

2,if directives
Default value: none; Using environment: Server,location
The directive is used to check whether a condition is compliant and, if the condition is met, to execute the statement within the curly braces. If directive does not support nesting, multiple conditions are not supported && and | | Processing.

Copy Code code as follows:

A. Variable name, the wrong value includes: empty string "" or any string starting with 0
B. Variable comparisons can use "=" (representing equals) and "!=" (means not equal to)
C. Regular expression pattern matching can use the "~*" and "~" symbols
D. " ~ "Symbol for matching case letters match
E. " ~* "notation for case-insensitive matching of uppercase and lowercase letters
F. "! ~ "and"!~* "the function of the symbol just and" ~ "," ~* "opposite, indicating mismatch
G. " -F "and"!-f "to determine whether a file exists
H. " -D "and"!-d "to determine if the directory exists
I. " -E "and"!-e "to determine whether a file or directory exists
J. " -X "and"!-x "to determine if the file is executable
K. Partial regular expressions can be accessed in (), with $1~$9

3,return directives

Syntax: return code; Use environment: server,location,if;
This directive is used to end the execution of the rule and return the status code to the client.
example, if the URL that is accessed ends with ". Sh" or ". Bash", the 403 status code is returned.

Copy Code code as follows:

Location ~. *. (Sh|bash)? $
{
return 403;
}

4,rewrite directives
Syntax: Rewrite regex replacement flag
Default value: none; Usage Environment: SERVER,LOCATION,IF
The directive redirects the URI according to an expression, or modifies the string. Directives are executed according to the order in which they are in the configuration file. Note An overriding expression is only valid for a relative path. If you want to match the host name, you should use the IF statement, as follows:

Copy Code code as follows:

if ($host ~* www. (. *) )
{
Set $host _without_www $;
Rewrite ^ (. *) $ http://$host _without_www$1 permanent;
}

The last parameter of the rewrite directive is a flag tag, and the support flag tag is:

1.last is equivalent to the [L] tag inside Apache, representing rewrite.
2.break After this rule is finished, the match is terminated and the following rule is no longer matched.
3.redirect returns 302 temporary redirection, and the browser address displays the URL address after the jump.
4.permanent Returns 301 Permanent Redirect, the browser address will display the URL address after the jump.

URI overrides are implemented using last and break, and the browser address bar does not change. And there is a slight difference, the alias directive must be marked with last, and the break tag is used when using the Proxy_pass directive.
The last mark after the execution of the rewrite rule for this article will server{...} The label restarts the request, and the break tag terminates the match after this rule match completes.

Generally in with location (location/{...}) or write the rewrite rule directly in the Server tab, use the last tag, or break in the non-root location (location/cms/{...}).

If the URI contains a parameter (/app/test.php?id=5), the parameter is automatically appended to the replacement string by default, and you can resolve the problem by adding the tag at the end of the replacement string.
For example:

Copy Code code as follows:

Rewrite ^/test (. *) $ http://www.jb51.net/home permanent;
Access Http://www.jb51.net/test?id=5 will jump to http://www.jb51.net/home?id=5

For example, if you redirect a similar url/photo/123456 to/path/to/photo/12/1234/123456.png

Copy Code code as follows:

Rewrite "/photo/([0-9]{2}) ([0-9]{2}) ([0-9]{2})"/path/to/photo/$1/$1$2/$1$2$3.png;

Note: If there are curly braces "{" or "}" inside the regular expression, you should use double quotes or single quotes. Linux Learning, http://linux.it.net.cn

5. Set directives
Syntax: Set variable value; Default value: none; Use environment: server,location,if;
The directive is used to define a variable and assign a value to a variable. The value of a variable can be a union of text, variables, and text variables.
Example: Set $varname "Hello World";

6,uninitialized_variable_warn directives
Syntax: Uninitialized_variable_warn on|off
Usage Environment: HTTP,SERVER,LOCATION,IF
This directive is used to turn warning messages on and off for uninitialized variables, and the default value is on.

Global variables that can be used by 7,nginx rewrite

Copy Code code as follows:

$args, $content _length, $content _type, $document _root, $document _uri, $host, $http _user_agent, $http _cookie, $limit _ Rate, $request _body_file, $request _method, $remote _addr,
$remote _port, $remote _user, $request _filename, $request _uri, $query _string, $scheme, $server _protocol, $server _addr, $ server_name, $server _port, $uri

Nginx Rewrite Rule Writing example
1. Redirect to a php file when the file and directory you are accessing does not exist

Copy Code code as follows:

if (!-e $request _filename)
{
Rewrite ^/(. *) $ index.php last;
}

2. Directory Swap/123456/xxxx ====>/xxxx?id=123456

Copy Code code as follows:

Rewrite ^/(d+)/(. +)//$2?id=$1 last;

3. If the client is using IE browser, redirect to the/ie directory

Copy Code code as follows:

if ($http _user_agent ~ msie)
{
Rewrite ^ (. *) $/ie/$1 break;
}

4. Prohibit access to multiple directories

Copy Code code as follows:

Location ~ ^/(cron|templates)/
{
Deny all;
Break
}

5. Prohibit access to documents beginning with/data

Copy Code code as follows:

Location ~ ^/data
{
Deny all;
}

6. Prohibit access to files with a. sh,.flv,.mp3 file suffix name

Copy Code code as follows:

Location ~. *. (Sh|flv|mp3) $
{
return 403;
}

7. Set browser cache time for certain types of files

Copy Code code as follows:

Location ~. *. (gif|jpg|jpeg|png|bmp|swf) $
{
Expires 30d;
}
Location ~. *. (JS|CSS) $
{
Expires 1h;
}

8. Set expiration time for Favicon.ico and robots.txt;

Here for Favicon.ico 99 days, robots.txt 7 days does not record 404 error log

Copy Code code as follows:

Location ~ (favicon.ico) {
Log_not_found off;
Expires 99d;
Break
}

Location ~ (robots.txt) {
Log_not_found off;
Expires 7d;
Break
}

9. Set the expiration time of a file; This is 600 seconds, and the access log is not logged

Copy Code code as follows:

Location ^~/html/scripts/loadhead_1.js {
Access_log off;
Root/opt/lampp/htdocs/web;
Expires 600;
Break
}

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.