標籤:
在 /usr/local/nginx/conf/nginx.conf 的預設 server 段中,保留預設的 location 資訊(之前測試的 location 配置刪除):
location / { root html; index index.html index.htm; }
在 /var/www 下建立 image 目錄:
[[email protected] ~]# cd /var/www[[email protected] www]# mkdir image
使用 wget 或者 ftp 在該目錄下下載或者傳輸一張圖片:test.jpg
修改 /usr/local/nginx/html/index.html,加上 <img src="./image/test.jpg">:
[[email protected] nginx]# vim html/index.html <!DOCTYPE html><html><head><title>Welcome to nginx!</title><style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; }</style></head><body><img src="./image/test.jpg"><h1>Welcome to nginx!</h1><p>If you see this page, the nginx web server is successfully installed andworking. Further configuration is required.</p><p>For online documentation and support please refer to<a href="http://nginx.org/">nginx.org</a>.<br/>Commercial support is available at<a href="http://nginx.com/">nginx.com</a>.</p><p><em>Thank you for using nginx.</em></p></body></html>
平滑重啟 nginx。
由於 /usr/local/nginx/html/ 目錄下並沒有 image 目錄,因此訪問 192.168.254.100 時,頁面上的圖片是無法顯示的:
直接存取圖片地址:
此時在 location 配置下添加正則匹配的 location 配置(第 2 段),此時的 location 配置為:
location / { root html; index index.html index.htm; } location ~ image { root /var/www/; index index.html; }
平滑重啟 nginx。
訪問 http://192.168.254.100/image/test.jpg,正則匹配和一般匹配都能匹配上該 uri 的時候,優先正則匹配:
/var/www/image 目錄下的圖片顯示了。
直接存取 http://192.168.254.100/image/test.jpg:
匹配過程是:正則匹配中的 image 能夠匹配到 uri 中的 /image/test.jpg,則正則匹配發揮作用,真正訪問的是 /var/www/images/test.jpg
再測試,當多個普通匹配都能匹配到 uri ,哪個匹配能真正發揮作用(比較第 1 段和第 2 段)?
/usr/local/nginx/conf/nginx.conf:
location / { root html; index index.html index.htm; } location /foo { root /var/www; index index.htm index.html; } location ~ image { root /var/www/; index index.html; }
此時 /var/www 目錄下有 foo 目錄,下面有檔案 index.htm : i‘m /var/www/index.htm
對於 uri "/foo",兩個 location 的 patt 都能匹配,即 "/" 和 "/foo" 都能左首碼匹配 "/foo",
訪問 http://192.168.254.100/foo:
即
location /foo { root /var/www; index index.htm index.html; }
發揮了作用,原因是 "/foo" 更長,因此使用 "/foo" 的 location 進行匹配。
Nginx 筆記與總結(7)Location:正則匹配