一、動靜分離
nginx的動靜分離簡單來說就是把動態和靜態的請求分開。有的請求是請求靜態資源的,有的請求是請求動態資源的,把這兩個請求分開。比如請求一個圖片,就是一個靜態的資源,這個圖片可以放在一個靜態資源服務器上,發送圖片的請求經過nginx轉發到這個靜態資源服務器上給出響應。比如從數據庫中查詢一個用戶信息,是動態資源請求。
1.準備靜態資源:
創建兩個目錄:
data/www.*.html
data/images/*.jpg
2.nginx.conf配置:
server {
listen 9003;
server_name localhost;
location / {
root data/www;
}
location /images/ {
root data/;
}
}
解釋:
1) location / { root data/www;} :瀏覽器輸入www/a.html時,沒有其他的路徑來匹配時,默認會匹配到location / 這個路徑。
2) root:在root配置的目錄後面跟上url組成對應的文件路徑,比如訪問localhost:9003/index.html,經過nginx轉換成localhost:9003/data/www/index.html
3) ps:location /images/ { root data/images;} 這麼寫是不對的,root data/images;多寫了個images。應該是data/;就行了。爲什麼呢?因爲url中的/images/2.jpg匹配到location /images/之後,將/images/2.jpg就拼接在root的配置data/images後面就成了data/images/images/2.jpg。所以root配置寫成data/;就行了。
總結:通過url去匹配靜態資源即可。將動態資源和動態資源的請求url做有規律的一些識別分開即可。比如靜態資源:static。
3.測試
瀏覽器分別訪問:http://localhost:9003/index.html http://localhost:9003/images/2.jpg 正確訪問,測試OK
---