location指令的做用是根據用戶的請求的URL來執行不一樣的應用html
location [ = | ~ | ~* | ^~ ] uri { ....... }
[ = | ~ | ~* | ^~ ] :匹配的標識(在這裏面 ‘~’ 用於區分大小寫,‘~*’ 不區分大小寫,'^~' 是在作完常規檢查後不檢查正則匹配)nginx
locarion = / { [ configuration A ] } # 用戶訪問 / 的時候,匹配configuration A locarion / { [ configuration B ] } # 用戶訪問 /index.html 的時候,匹配configuration B locarion /documents/ { [ configuration C ] } # 用戶訪問 /documents/documents.html 的時候,匹配configuration C locarion ^~ /images/ { [ configuration D ] } # 用戶訪問 /images/1.gif 的時候,匹配configuration D locarion ~* \.(gif|jpg|jpeg)$ { [ configuration E ] } # 用戶訪問 /documents/1.gif 的時候,匹配configuration E
以www.brian.com虛擬主機爲例,修改brian.conf配置文件:bash
[root@Nginx www_date]# cat brian.conf server { listen 80; server_name www.brian.com brian.com; root html/brian; location / { return 401; } location = / { return 402; } location /documents/ { return 403; } location ^~ /images/ { return 404; # 匹配任何以/images/開頭的查詢 } location ~* \.(gif|jpg|jpeg)$ { return 405; # 匹配任何以 gif、jpg、jpeg結尾的請求 } access_log logs/brian.log main gzip buffer=128k flush=5s; }
檢查語法:curl
[root@Nginx conf]# ../sbin/nginx -t nginx: the configuration file /opt/nginx//conf/nginx.conf syntax is ok nginx: configuration file /opt/nginx//conf/nginx.conf test is successful
平滑重啓:測試
[root@Nginx conf]# ../sbin/nginx -s reload
Linux客戶端測試:網站
[root@Nginx conf]# curl www.brian.com/ # 對應location = / <html> <head><title>402 Payment Required</title></head> # 返回402 <body bgcolor="white"> <center><h1>402 Payment Required</h1></center> <hr><center>nginx/1.6.3</center> </body> </html> [root@Nginx conf]# curl www.brian.com/index.html # 對應location / <html> <head><title>401 Authorization Required</title></head> # 返回401 <body bgcolor="white"> <center><h1>401 Authorization Required</h1></center> <hr><center>nginx/1.6.3</center> </body> </html> [root@Nginx conf]# curl www.brian.com/documents/ #對應location /documents/ <html> <head><title>403 Forbidden</title></head> # 返回403 <body bgcolor="white"> <center><h1>403 Forbidden</h1></center> <hr><center>nginx/1.6.3</center> </body> </html> [root@Nginx conf]# curl www.brian.com/images/1.gif # 對應location ^~ /images/ <html> <head><title>404 Not Found</title></head> # 返回404 <body bgcolor="white"> <center><h1>404 Not Found</h1></center> <hr><center>nginx/1.6.3</center> </body> </html> [root@Nginx conf]# curl www.brian.com/documents/1.gif # 對應location ~* \.(gif|jpg|jpeg)$ <html> <head><title>405 Not Allowed</title></head> # 返回405 <body bgcolor="white"> <center><h1>405 Not Allowed</h1></center> <hr><center>nginx/1.6.3</center> </body> </html>