使用nginx作為css,js,image靜態檔案的伺服器
阿新 • • 發佈:2019-01-29
概述
最近web專案將圖片,css,js等一些靜態檔案都移出去用svn統一管理了。所以在開發web專案時需要自己匯入靜態檔案,或者配置一個HTTP服務來訪問svn下的靜態資源。當然不會每次都自己拷貝靜態檔案到專案了,nginx是一個不錯的選擇。
一些命令
tasklist /fi"imagename eq nginx.exe"
顯示nginx在系統中的程序
其中一個是主程序,另一個是工作程序。
其他命令:
- nginx -s stop 快速退出
- nginx -s quit 優雅退出
- nginx -s reload 更換配置,啟動新的工作程序,優雅的關閉以往的工作程序
- nginx -s reopen 重新開啟日誌檔案
簡單的配置
靜態資源本地路徑:E:\svn\web及檔案如下:
PS:習慣用linux下的ls命令,而在windows裡面不能識別這個命令。為了能在windows裡面使用ls命令,可以在C:\Windows 中加入一個檔案ls.bat,內容如下
@echo off
dir
這樣就能在windows下用ls了。
配置檔案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 {
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)/{
root E:\svn\web;
access_log off;
expires 30d;}#error_page 404 /404.html;# redirect server error pages to the static page /50x.html#
error_page 500502503504/50x.html;
location =/50x.html {
root html;}}}
主要是在server監控的80埠下新增一個location來指定靜態檔案路徑,location 這個指令允許根據URI進行不同的配置。它可以使用字串和正則表示式進行配置。如果使用正則,就必須使用字首。
- “~” 匹配時區分大小寫
- “~*” 匹配時不區分大小寫
- “=” 精確匹配字元和字串
-
“^~” 例如: ^~ /images/ 匹配到任何以images開頭的,便停止搜尋。
location ~ ^/(images|javascript|js|css|flash|media|static)/ { #請求的根文件 root E:\svn\web; #過期時間 expires 30d; }
這裡的location匹配以images等開頭的路徑。如果檔案路徑不存在,會提示404錯誤。例如:http://localhost:80/css/detail.css。會找到E:\svn\web\css\detail.css
可以正常訪問到檔案。http://localhost:80/test/test.css。會提示404,雖然存在這個E:\svn\web\test\test.css檔案。
參考資料
- worker_processes 1;
- events {
- worker_connections 1024;
- }
- http {
- sendfile on;
- tcp_nodelay on;
- keepalive_timeout 30;
- server {
- listen 80;
- server_name localhost;
- charset utf-8;
- access_log logs/host.access.log;
- root D:/Program/Apache-tomcat-6.0.41/webapps/test;
- autoindex on;
- autoindex_exact_size off;
- autoindex_localtime on;
- }
- }