One. Regular expression match, where: * ~ is case-sensitive matching * ~* is a case-insensitive match * !~ and !~* are case-sensitive and case-insensitive mismatches, respectively Two. file and directory match, where: * -f and !-f are used to determine if a file exists * -d and !-d are used to determine if a directory exists * -e and !-e are used to determine if a file or directory exists * -x and !-x are used to determine whether a file is executable or not 3. The last parameter of the rewrite instruction is the flag mark, which is marked with: 1.last is equivalent to the [L] mark in apache, which means rewrite. 2. Break After the matching of this rule is completed, the matching will be terminated and the subsequent rules will no longer be matched. 3.redirect returns 302 temporary redirect, and the browser address will display the URL address after the jump. 4.permanent return 301 permanent redirect, the browser address will display the URL address after the jump.
Use last and break to implement URI rewrites, and the browser address bar remains unchanged. And there is a slight difference between the two, using the alias command must be marked with last; When using proxy_pass directives, you need to use the break tag. After the last tag is executed in this rewrite rule, it will be on the server{......} tag re-initiates the request, while the break tag terminates the match after the rule match is complete. For example: if we redirect a URL like /photo/123456 to /path/to/photo/12/1234/123456.png rewrite "/photo/([0-9]{2})([0-9]{2})([0-9]{2})"/path/to/photo/$1/$1$2/$1$2$3.png ;
Four. NginxRewrite rule
1.break command Usage environment: server, location, if; The directive completes the current ruleset and no longer handles the rewrite directive.
2. If directive Usage environment: server, location This instruction is used to check whether a condition is met, and if so, execute the statement inside the curly braces. The If command does not support nesting, and does not support multiple conditions && and || Treatment.
3. return command syntax: returncode ; Usage environment: server, location, if; This instruction is used to end the execution of the rule and return a status code to the client. Example: If the visited URL ends in ".sh" or ".bash", a 403 status code is returned location ~ .*\. (sh|bash)?$
{ return 403;
}
4. rewrite command Syntax: rewriteregex replacement flag Usage environment: server, location, if This directive redirects the URI based on the expression, or modifies the string. Instructions are executed in the order in the configuration file. Note that rewriting expressions is only valid for relative paths. If you want to pair hostnames, you should use if statements, for example below: if( $host ~* www\.(. *) )
{ set $host_without_www $1; rewrite ^(.*)$ http://$host_without_www$1permanent;
}
5.Set command Syntax: setvariable value; Default: none; Usage environment: server, location, if; This directive is used to define a variable and assign a value to it. The value of a variable can be text, variable, or union of text variables. Example: set$varname "hello world";
6.Uninitialized_variable_warn instructions Syntax: uninitialized_variable_warnon|off Usage environment: http, server, location, if This command is used to turn on and off the warning message for uninitialized variables, and the default value is On.
Five. Nginx Rewrite rule writing example 1. When the accessed file and directory do not exist, redirect to a certain php file if( !-e $request_filename )
{ rewrite ^/(.*)$ index.php last;
}
2. Directory swap /123456/xxxx ====> /xxxx?id=123456 rewrite ^/(\d+)/(.+)/ /$2?id=$1 last;
3. If the client is using IE browser, it redirects to the /ie directory if( $http_user_agent ~ MSIE)
{ rewrite ^(.*)$ /ie/$1 break;
}
4. Disable access to multiple directories location ~ ^/(cron|templates)/
{ deny all; break;
}
5. Disable access to files starting with /data location ~ ^/data
{ deny all;
}
6. Prohibit access to files with file suffix names .sh, .flv, .mp3 location ~ .*\. (sh|flv|mp3)$
{ return 403;
}
7. Set the browser cache time for certain types of files location ~ .*\. (gif|jpg|jpeg|png|bmp|swf)$
{ expires 30d;
} location ~ .*\. (js|css)$
{ expires 1h;
}
8. Set expiration times for favicon.ico and robots.txt; Here, the favicon.ico is 99 days, and the robots.txt is 7 days, and the 404 error log is not logged 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 certain document; This is 600 seconds, and access logs are not recorded location ^~ /html/scripts/loadhead_1.js { access_log off; root /opt/lampp/htdocs/web; expires 600; break;
}
10. Anti-hotlink files and set expiration times Return412 here is a custom HTTP status code, which defaults to 403, which is convenient for finding the correct hotlink request “rewrite ^/ ; "Shows an image of an anti-hotlink “access_log off;” No access logs are recorded, reducing stress "Expires 3D" 3 days of browser cache for all files
location ~*^.+\. (jpg|jpeg|gif|png|swf|rar|zip|css|js)$ { valid_referers none blocked *.xx.com*.xx.net localhost 208.97.167.194; if ($invalid_referer) { rewrite ^/ ; return 412; break;
} access_log off; root /opt/lampp/htdocs/web; expires 3d; break;
}
11. Only allow fixed IP access to the website with a password
root /opt/htdocs/www; allow 208.97.167.194; allow 222.33.1.2; allow 231.152.49.4; deny all; auth_basic “C1G_ADMIN”; auth_basic_user_file htpasswd;
12Convert files in multi-level directories into one file to enhance SEO effects
/job-123-456-789.html 指向/job/123/456/789.html
rewrite^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last;
13. Redirect when files and directories do not exist:
if (!-e $request_filename) { proxy_pass http://127.0.0.1;
}
14. Point a folder in the root directory to the level 2 directory For example, /shanghaijob/ points to /area/shanghai/ If you change last to permanent, then the browser address bar will be /location/shanghai/ rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last; The problem with the above example is that it will not match when accessing /shanghai rewrite ^/([0-9a-z]+)job$ /area/$1/ last; rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last; This way/shanghai is also accessible, but the relative links in the page are not available, If ./list_1.html real address is /area/shanghia/list_1.html will become /list_1.html, making it inaccessible. Then I can't add automatic jumping (-d $request_filename) has a condition that it must be a real directory, and my rewrite is not, so it has no effect if (-d $request_filename){ rewrite ^/(.*)([^/])$ http://$host/$1$2/permanent;
} It's easy to do after knowing the reason, let me jump manually rewrite ^/([0-9a-z]+)job$ /$1job/permanent; rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last;
15. Domain name jumping server
{ listen 80; server_name jump.linuxidc.com; index index.html index.htm index.php; root /opt/lampp/htdocs/www; rewrite ^/ http://www.xx.com/; access_log off;
}
16. Multi-domain turning server_name www.xx.comwww.xx.com; index index.html index.htm index.php; root /opt/lampp/htdocs; if ($host ~ "linuxidc\.net") { rewrite ^(.*) http://www.xx.com$1permanent;
}
6. nginx global variables arg_PARAMETER #这个变量包含GET请求中, if there is a variable PARAMETER. args #这个变量等于请求行中 (GET request) parameters, e.g., foo=123&bar=blahblah; binary_remote_addr #二进制的客户地址. body_bytes_sent #响应时送出的body字节数数量. This data is accurate even if the connection is interrupted. content_length #请求头中的Content-length field. content_type #请求头中的Content-Type field. cookie_COOKIE #cookie the value of the COOKIE variable document_root #当前请求在root指令中指定的值. document_uri #与uri相同. host #请求主机头字段, otherwise the server name. hostname #Set to themachine’s hostname as returned by gethostname http_HEADER is_args #如果有args参数, this variable is equal to "?", otherwise equal to "", null value. http_user_agent #客户端agent信息 http_cookie #客户端cookie信息 limit_rate #这个变量可以限制连接速率. query_string #与args相同. request_body_file #客户端请求主体信息的临时文件名. request_method #客户端请求的动作, usually GET or POST. remote_addr #客户端的IP地址. remote_port #客户端的端口. remote_user #已经经过Auth Username validated by the Basic Module. request_completion #如果请求结束, set it to OK. Empty when the request is not finished or if the request is not the last in the request chain. request_method #GET或POST request_filename #当前请求的文件路径, generated by root or alias directives and URI requests. request_uri #包含请求参数的原始URI, it does not contain the hostname, e.g., "/foo/bar.php?arg=baz". cannot be modified. scheme #HTTP方法 (e.g. http, https). server_protocol #请求使用的协议, usually HTTP/1.0 or HTTP/1.1. server_addr #服务器地址, this value can be determined after a system call is completed. server_name #服务器名称. server_port #请求到达服务器的端口号.
Seven. Correspondence between Apache and Nginx rules Apache's RewriteCond corresponds to Nginx's if Apache's RewriteRule corresponds to Nginx's rewrite Apache's [R] corresponds to Nginx's redirect [P] in Apache corresponds to last in Nginx Apache's [R,L] corresponds to Nginx's redirect Apache's [P,L] corresponds to Nginx's last Apache's [PT,L] corresponds to Nginx's last
For example, allow a specified domain name to access this site, and always turn to www.xx.com other domain names Apache: RewriteCond %{HTTP_HOST} !^(.*?) \.aaa\.com$[NC] RewriteCond %{HTTP_HOST} !^localhost$ RewriteCond %{HTTP_HOST}!^192\.168\.0\. (.*?) $ RewriteRule ^/(.*)$ http://www.xx.com[R,L]
Nginx: if( $host ~* ^(.*)\.aaa\.com$ )
{ set $allowHost ‘1’;
} if( $host ~* ^localhost )
{ set $allowHost ‘1’;
} if( $host ~* ^192\.168\.1\.(. *?) $ )
{ set $allowHost ‘1’;
} if( $allowHost !~ ‘1’ )
{ rewrite ^/(.*)$ http://www.xx.comredirect ;
}
|