Nginx's location configuration detailed

Source: Internet
Author: User
Tags browser cache domian
Syntax rules: location [=|~|~*|^~]/uri/{...}
= The beginning indicates an exact match
The beginning of the ^~ indicates that the URI begins with a regular string and is understood to match the URL path. Nginx does not encode the URL, so the request is/STATIC/20%/AA and can be matched by the rule ^~/static//aa (note is a space).
~ starts with a case-sensitive regular match
~* begins with a case-insensitive regular match
!~ and!~*, respectively, are case insensitive and case-insensitive mismatches
/Universal match, any request will match to.
Multiple location configuration in the case of matching order for (resources, not actually validated, try to know, do not adhere to, for reference only):
First match =, second match ^~, followed by regular matching in file order, finally to/Universal match. When a match is successful, stop the match and process the request according to the current matching rule.
example, there are the following matching rules:
Location =/{ 
#规则A 
} 
location =/login { 
#规则B 
} 
location ^~/static/{ 
#规则C 
} 
Location ~ \. (GIF|JPG|PNG|JS|CSS) $ { 
#规则D 
} 
location ~* \.png$ { 
#规则E 
} 
location!~ { 
# Rule F 
} 
location!~* \.xhtml$ { 
#规则G 
} 
location/{ 
#规则H 

The resulting effect is as follows:
Access to the root directory/, such as http://localhost/will match rule a
Access http://localhost/login match Rule b,http://localhost/register match rule H
Access to http://localhost/static/a.html will match rule C
Access to Http://localhost/a.gif, Http://localhost/b.jpg will match the rules D and rule e, but the rule D order takes precedence, and rule e does not work, and http://localhost/static/c.png Then match precedence to rule C
Access to Http://localhost/a.PNG matches rule e without matching rule d because rule e is case-insensitive.
Access http://localhost/a.xhtml does not match rule f and rule g,http://localhost/a.xhtml does not match rule G because it is case-insensitive. Rule f, rule G is an exclusion, conforms to matching rules but does not match, so think about where the actual application will be used.
The access http://localhost/category/id/1111 is ultimately matched to rule H because none of the above rules match, and this should be the Nginx forwarding request to the backend application server, such as fastcgi (PHP), Tomcat (JSP), Nginx exists as a directional proxy server.
Therefore, in actual use, individuals feel that there are at least three matching rule definitions, as follows:
#直接匹配网站根, through the domain name to visit the home page more frequently, use this will speed up processing, said the official website. 
#这里是直接转发给后端应用服务器了, can also be a static home 
# The first required rule 
location =/{ 
proxy_pass http://tomcat:8080/index 
} 

# The second required rule is to process the static file request, which is nginx as the strength of the HTTP server 
# There are two configuration modes, directory matching or suffix matching, optional or with 
location ^~/static/{ 
root/ webroot/static/; 
} 
Location ~* \. (Gif|jpg|jpeg|png|css|js|ico) $ { 
root/webroot/res/; 
} 

#第三个规则就是通用规则, to forward the dynamic request to the backend application server 
#非静态文件请求就默认是动态请求, according to the actual grasp 
of the #毕竟目前的一些框架的流行, with a 
. php,.jsp suffix is rare. Location/{ 
Proxy_pass http://tomcat:8080/ 

Additional information not tested:
Third, rewrite grammar
last– basically use this flag.
break– abort Rewirte, do not continue to match
redirect– returns the temporarily redirected HTTP status 302
permanent– returns HTTP status for permanent redirection 301
Note: The biggest difference between last and break is
-The break is to terminate the current location rewrite detection and no longer location match-last is to terminate the rewrite detection of the current location, but will continue to retry the location match and process the rewrite rule in the block
1. The following are the expressions that you can use to determine:
-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
2, the following is a global variable that can be used as a judgment
$args #这个变量等于请求行中的参数.
$content _length #请求头中的Content-length field.
$content _type #请求头中的Content-type field.
$document _root #当前请求在root指令中指定的值.
$host #请求主机头字段, otherwise the server name.
$http _user_agent #客户端agent信息
$http _cookie #客户端cookie信息
$limit _rate #这个变量可以限制连接速率.
$request _body_file #客户端请求主体信息的临时文件名.
$request _method #客户端请求的动作, usually a get or post.
$remote _addr #客户端的IP地址.
$remote _port #客户端的端口.
$remote the user name _user #已经经过Auth Basic module validation.
$request _filename #当前请求的文件路径, generated by root or alias directives and URI requests.
$query _string #与 $args the same.
$scheme #HTTP方法 (e.g. Http,https).
$server _protocol #请求使用的协议, usually http/1.0 or http/1.1.
$server _addr #服务器地址, this value can be determined once the system call has been completed.
$server _name #服务器名称.
$server _port #请求到达服务器的端口号.
$request _uri #包含请求参数的原始URI, does not contain host names, such as "/foo/bar.php?arg=baz".
$uri #不带请求参数的当前URI, $uri does not contain a host name, such as "/foo/bar.html".
$document _uri #与 $uri the same.
Example: http://localhost:88/test1/test2/test.php
$host: localhost
$server _port:88
$request _uri:http://localhost:88/test1/test2/test.php
$document _uri:/test1/test2/test.php
$document _root:d:\nginx/html
$request _filename:d:\nginx/html/test1/test2/test.php
Four, redirect grammar
Multi-Directory conversion parameters
ABC.DOMIAN.COM/SORT/2 => abc.domian.com/index.php?act=sort&name=abc&id=2
1. if ($host ~* (. *) \.domain\.com) {
2. Set $sub _name $;
3. Rewrite ^/sort\/(\d+) \/?$/index.php?act=sort&cid= $sub _name&id=$1 last;
4.}
Directory swap
/123456/xxxx->/xxxx?id=123456
1. Rewrite ^/(\d+)/(. +)//$2?id=$1 last;
For example, the following settings Nginx are redirected to the/nginx-ie directory using the user's use of IE:
1. if ($http _user_agent ~ msie) {
2. Rewrite ^ (. *) $/nginx-ie/$1 break;
3.}
Directory automatically add "/"
1. if (D-$request _filename) {
2. Rewrite ^/(. *) ([^/]) $ http://$host/$1$2/permanent;
3.}
Prohibit htaccess
1. Location ~/\.ht {
2. Deny all;
3.}
Prohibit multiple directories
1. Location ~ ^/(cron|templates)/{
2. Deny all;
3. break;
4.}
Prohibit files that start with/data
Can prohibit/data/under the multi-level directory. Log.txt and other requests;
1. Location ~ ^/data {
2. Deny all;
3.}
Prohibit a single directory
cannot be forbidden. Log.txt can request
1. location/searchword/cron/{
2. Deny all;
3.}
Prohibit individual files
1. Location ~/data/sql/data.sql {
2. Deny all;
3.}
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
1. Location ~ (favicon.ico) {
2. Log_not_found off;
3. Expires 99d;
4. Break;
5.}
6.
7. Location ~ (robots.txt) {
8. Log_not_found off;
9. Expires 7d;
break;
11.}
Sets the expiration time for a file; This is 600 seconds, and the access log is not logged
1. Location ^~/html/scripts/loadhead_1.js {
2. Access_log off;
3. Root/opt/lampp/htdocs/web;
4. Expires 600;
5. Break;
6.}
File anti-hotlinking and set expiration time
The return 412 here is a custom HTTP status code, the default is 403, to easily find the right hotlinking request
"Rewrite ^/http://leech.c1gstudio.com/leech.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
1. Location ~* ^.+\. (JPG|JPEG|GIF|PNG|SWF|RAR|ZIP|CSS|JS) $ {
2. Valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194;
3. if ($invalid _referer) {
4. Rewrite ^/http://leech.c1gstudio.com/leech.gif;
5. return 412;
6. Break;
7.}
8. Access_log off;
9. Root/opt/lampp/htdocs/web;
Expires 3d;
One. break;
12.}
Only fixed IP access to the site, plus password
1. root/opt/htdocs/www;
2. Allow 208.97.167.194;
3. Allow 222.33.1.2;
4. Allow 231.152.49.4;
5. Deny all;
6. Auth_basic "C1g_admin";
7. Auth_basic_user_file htpasswd;
Turn the files in a multilevel directory into a file to enhance the SEO effect
/job-123-456-789.html Point to/job/123/456/789.html
1. Rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+) \.html$/job/$1/$2/jobshow_$3.html;
Point a folder in the root directory to level 2 directory
such as/shanghaijob/point to/area/shanghai/
If you change the last to permanent, then the browser address bar is/location/shanghai/
1. Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2 last;
The problem with the example above is that it will not match when accessing the/shanghai
1. Rewrite ^/([0-9a-z]+) job$/area/$1/last;
2. Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2 last;
This/shanghai can also be accessed, but the relative links in the page are not available.
such as./list_1.html real address is/area/shanghia/list_1.html will become/list_1.html, lead to inaccessible.
Then I'll go with the automatic jump.
(-D $request _filename) It has a condition that is required for the real directory, and my rewrite is not, so no effect
1. if (D-$request _filename) {
2. Rewrite ^/(. *) ([^/]) $ http://$host/$1$2/permanent;
3.}
Know the reason to do it, let me manually jump it
1. Rewrite ^/([0-9a-z]+) job$/$1job/permanent;
2. Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2 last;
redirect When files and directories do not exist:
1. if (!-e $request _filename) {
2. Proxy_pass http://127.0.0.1;
3.}
Domain Jump
1. Server
2. {
3. Listen 80;
4. Server_Name jump.c1gstudio.com;
5. Index index.html index.htm index.php;
6. root/opt/lampp/htdocs/www;
7. Rewrite ^/http://www.c1gstudio.com/;
8. Access_log off;
9.}
Multi-domain Direction
1. server_name www.c1gstudio.com www.c1gstudio.net;
2. Index index.html index.htm index.php;
3. Root/opt/lampp/htdocs;
4. if ($host ~ "C1gstudio\.net") {
5. Rewrite ^ (. *) http://www.c1gstudio.com$1 permanent;
6.}
Level three domain jump
1. if ($http _host ~* "^ (. *) \.i\.c1gstudio\.com$") {
2. Rewrite ^ (. *) http://top.yingjiesheng.com$1;
3. break;
4.}
Domain name Mirror to
1. Server
2. {
3. Listen 80;
4. Server_Name mirror.c1gstudio.com;
5. Index index.html index.htm index.php;
6. root/opt/lampp/htdocs/www;
7. Rewrite ^/(. *) http://www.c1gstudio.com/$1 last;
8. Access_log off;
9.}

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.