搭建靜態資源站包括以下幾部分:
- root指令與alias指令的區別
- 使用gzip壓縮資源
- 如何訪問指定目錄下的全部資源文件
- 如何限制訪問流量
- 如何自定義log日志
root指令與alias指令的區別
我們的網站靜態資源放到 /home/wwwroot/demo 目錄下
root@2a33e33fa785:/home/wwwroot/demo# ls
about.html about1.html css fonts gallery.html images index.html js typography.html
nginx.conf 文件
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location /demo/ { root /home/wwwroot;
#alias /home/wwwroot/demo/; } } }
上面的配置文件中 root和alias 指令配置完之后實現的效果是一樣的,其實用的區別在於:
- 使用root指令時,訪問 http://ip:端口號/demo/index.html 時,nginx回去root 指定的目錄下按照url地址來尋找index.html文件
- 使用 alias 指令就相當於為 /demo/ 起了個別名 /demo/ 與 alias 指定的目錄是等同的所以當同樣訪問 http://ip:端口號/demo/index.html 時,nginx 獲取 alias 指定的目錄下尋找 index.html 文件
使用gzip壓縮
#開啟gzip gzip on; #低於1kb的資源不壓縮 gzip_min_length 1k; #壓縮級別【1-9】,越大壓縮率越高,同時消耗cpu資源也越多,建議設置在4左右。 gzip_comp_level 3; #需要壓縮哪些響應類型的資源,多個空格隔開。不建議壓縮圖片,下面會講為什么。 gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
使用前 index.html 的請求大小
開啟gzip之后
訪問指定目錄下的全部資源文件
在 server 或者 http 或者 location 指令中 加入 autoindex on; 指令
限制訪問流量
添加 set $limit_rate 1k 限制請求每秒只能傳輸1kB數據,這時我們訪問頁面會明顯感覺到很慢
設置log日志
設置日志格式 log_format 模板名稱 日志中包含的內容 注意:模板中所保存的內容可以是nginx模塊及第三方模塊提供的任意參數內容,例如 這里 提供的變量都可以存儲起來
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 日志路徑 模板名稱;
access_log logs/host.access.log main;
最后是完整的配置文件
worker_processes 1; events { 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"'; sendfile on; keepalive_timeout 65; gzip on; gzip_min_length 1k; gzip_comp_level 3; gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css; server { listen 80; server_name localhost; access_log logs/host.access.log main; location / { root /home/wwwroot/demo/; autoindex on; set $limit_rate 1k; } } }