之前項目所有靜態文件都和項目捆綁在一起的,存放在webapp下面,這樣雖然在獲取的時候很方便,但是web項目現在越來越大,靜態資源文件也越來越多,導致服務器的性能也越來越低了,特別是當獲取大量圖片的時候,直線下降。
出現問題就要解決,想到用Nginx去搭建靜態服務器是個不錯的選擇,那麼就開始吧!
第一步:
去Nginx官網下載Nginx,並且安裝好,當然你也可以下載免安裝包。
第二步:
啓動Nginx, 知道安裝Nginx目錄,我這裏是在:D:\nginx,然後雙擊nginx.exe即可。如果想關閉,則在當前目錄下執行命令nginx -s quit 即可。
第三步:重點來了,重點來了,重點來了!!!
找到Nginx目錄下的conf文件夾(D:\nginx\conf),修改nginx.conf文件,以下是我的修改
#user nobody; worker_processes 1;#推薦worker數爲cpu核數,避免cpu不必要的上下文切換 events { #表示每個worker進程所能建立連接的最大值 #一個nginx最大的連接數max=worker_connections*worker_processes; #對於http請求本地資源最大併發數量爲max #如果http作爲反向代理,最大併發數爲max/2。因爲每個併發會建立與客戶端的連接和與後端服務的連接,會佔用兩個連接。 worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; keepalive_timeout 65; server { #監聽80端口 listen 80; server_name localhost; #charset koi8-r; access_log logs/host.access.log main; location / { root html; index index.html index.htm; } # serve static files(css|js|image..) # #這個地方是重點!!! #所有靜態文件開頭的請求,都會被重新指向 location ~ ^/(images|javascript|js|css|flash|media|static)/ { #指向資源所在的位置,這裏要特別注意的是,如果請求的是/images ,則C:\image目錄下面應該有個對應的C:\image\images目錄 root C:\image; access_log on; expires 30d; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }
其中要注意點的地方是:
#所有靜態文件開頭的請求,都會被重新指向 location ~ ^/(images|javascript|js|css|flash|media|static)/
#指向資源所在的位置,這裏要特別注意的是,如果請求的是/images ,則C:\image目錄下面應該有個對應的C:\image\images目錄,這個地方尤其重要,很容易就錯誤而且混淆。
root C:\image;
第四步:
我們可以在C:\image\images目錄裏面放入一張照片,123.jpg,然後打開瀏覽器輸入http://localhost/images/123.jpg 即可看到結果,是不是很簡單啊!!!