Nginx 中的 Location 指令 是NginxHttpCoreModule中重要指令。Location 指令,是用來為匹配的 URI 進行配置,URI 即語法中的”/uri/”,可以是字符串或正則表達式。但如果要使用正則表達式,則必須指定前綴。
nginx location語法
基本語法:location [=|~|~*|^~] /uri/ { … }
- = 嚴格匹配。如果這個查詢匹配,那么將停止搜索并立即處理此請求。
- ~ 為區分大小寫匹配(可用正則表達式)
- ~* 為不區分大小寫匹配(可用正則表達式)
- !~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配
- ^~ 如果把這個前綴用于一個常規字符串,那么告訴nginx 如果路徑匹配那么不測試正則表達式。
Location語法語法:location [=|~|~*|^~] /uri/ { … }
注:
1、~ 為區分大小寫匹配
2、~* 為不區分大小寫匹配
3、!~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配
例子:
location = / {# matches the query / only.# 只匹配 / 查詢。[ configuration A ]}location / {# matches any query, since all queries begin with /, but regular# expressions and any longer conventional blocks will be# matched first.# 匹配任何查詢,因為所有請求都已 / 開頭。但是正則表達式規則和長的塊規則將被優先和查詢匹配。[ configuration B ]}location ^~ /images/ {# matches any query beginning with /images/ and halts searching,# so regular expressions will not be checked.# 匹配任何已 /images/ 開頭的任何查詢并且停止搜索。任何正則表達式將不會被測試。[ configuration C ]}location ~* .(gif|jpg|jpeg)$ {# matches any request ending in gif, jpg, or jpeg. However, all# requests to the /images/ directory will be handled by# Configuration C.# 匹配任何已 gif、jpg 或 jpeg 結尾的請求。然而所有 /images/ 目錄的請求將使用 Configuration C。[ configuration D ]}
我的添加模式,動靜分離
location ^~ /(images|scripts|styles|upload)/ { root /www/abc.com/www/htdocs; expires 30d; } location ~*/.(gif|jpg|jpeg|png|css|ico|html)$ { root /www/abc.com/www/htdocs; expires 30d; }
如果要定義多個location,則可以有2種方式:
使用/ :location / { client_max_body_size 200m; proxy_connect_timeout 30; proxy_set_header Host $http_host; proxy_set_header x-forwarded-for $remote_addr; proxy_pass http://127.0.0.1:8008; } location /tmp/{ root /; internal; } 采用這種方式,/tmp可以放在/的下面,因為“/是匹配任何查詢,但是正則表達式規則和長的塊規則將被優先和查詢匹配”
使用~ /* : location ~ /tmp/ { root /tmp; internal; } location ~ /* { client_max_body_size 20m; proxy_connect_timeout 30; fastcgi_pass fpass; include fastcgi_params; } 采用這種方式,/tmp則必須放在~ /*這個前面,因為~是正則匹配的,正則匹配是有順序的,只要匹配上就不會再往下匹配了。除非在conf中有定義=或者^~,也就是說=和^~的優先級最高,如果匹配上,就不會再去匹配其它的規則了。