一、静态资源类型
Nginx作为静态资源Web服务器部署配置,传输非常的高效,常常用于静态资源处理、请求、动静分离。
非服务器动态运行生成的文件属于静态资源。
类型 | 种类 |
浏览器端渲染 | HTML、CSS、 JS |
图片 | JPEG、 GIF、PNG |
视频 | FLV 、Mp4 |
文件 | TXT、 任意下载文件 |
二、静态资源场景
静态资源传输延迟最小化
CDN: 静态资源请求、 静态资源回源
三、 静态资源配置语法
1. 文件读取高效 sendfile
Syntax: sendfile on | off; Default: sendfile off; Context: http, server, location, if in location
2. 提高网络传输效率nopush: 在sendfile 开启情况下,提高网络包的"传输效率"
Syntax: tcp_nopush on | off; Default: tcp_nopush off; Context: http, server, location Enables or disables the use of the TCP_NOPUSH socket option on FreeBSD or the TCP_CORK socket option on Linux. The options are enabled only when sendfile is used. Enabling the option allows sending the response header and the beginning of a file in one packet, on Linux and FreeBSD 4.*; sending a file in full packets.
3. tcp_nodelay : 与tcp_nopush对应的配置; 在 keepalive 连接下,提高网络传输的"实时性"
Syntax: tcp_nodelay on | off; Default: tcp_nodelay on; Context: http, server, location
The option is enabled when a connection is transitioned into the keep-alive state. Additionally, it is enabled on SSL connections, for unbuffered proxying, and for WebSocket proxying.
四、静态资源文件压缩
Nginx将响应报文发送至客户端之前可以启用压缩功能,这能够有效地节约带宽,并提高响应至客户端的速度。
gzip压缩配置语法:
传输压缩,Enables or disables gzipping of responses
Syntax: gzip on | off; Default: gzip off; Context: http, server, location, if in location
gzip压缩比率配置: 压缩本身消耗服务端性能。
Syntax: gzip_comp_level level; Default: gzip_comp_level 1; Context: http, server, location Sets a gzip compression level of a response. Acceptable values are in the range from 1 to 9.
gzip压缩协议版本: 压缩使用http哪个协议,主流版本1.1。
Syntax: gzip_http_version 1.0 | 1.1; Default: gzip_http_version 1.1; Context: http, server, location
Sets the minimum HTTP version of a request required to compress a response.
gzip_static扩展: 预读gzip功能。
Syntax: gzip_static on | off | always; Default: gzip_static off; Context: http, server, location Enables ("on") or disables ("off") checking the existence of precompressed files. The following directives are also taken into account: gzip_http_version, gzip_proxied, gzip_disable, and gzip_vary. With the "always" value (1.3.6), gzipped file is used in all cases, without checking if the client supports it. It is useful if there are no uncompressed files on the disk anyway or the ngx_http_gunzip_module is used. The files can be compressed using the gzip command, or any other compatible one. It is recommended that the modification date and time of original and compressed files be the same.
案例:
location ~ .*\.(jpg|gif|png)$ {
gzip on;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/json application/x-javascript application/xml image/gif image/png image/jpeg;
root /application/nginx/shop/images;
}
五、静态资源浏览器缓存
HTTP协议定义的缓存机制(如: Expires; Cache-control等) ngx_http_headers_module模块
- 浏览器没有缓存: 浏览器请求 -> 无缓存 -> 请求WEB服务器 -> 请求响应 -> 呈现
- 浏览器有缓存: 浏览器请求 -> 有缓存 -> 校验过期 -> 是否有更新 -> 呈现
- 校验是否过期:
- Expires HTTP1.0, Cache-control(max-age) HTTP1.1
- 协议中Etag头信息校验 Etag()
- Last-Modified 头信息校验 Last-Modified(具体时间)
- 校验是否过期:
缓存配置语法expires: 作用: 添加 Cache-Control Expires头
Syntax: expires [modified] time; expires epoch | max | off; Default: expires off; Context: http, server, location, if in location
Enables or disables adding or modifying the "Expires" and "Cache-Control" response header fields provided that the response code equals 200, 201 (1.3.10), 204, 206, 301, 302, 303, 304, 307 (1.1.16, 1.0.13), or 308 (1.13.0). The parameter can be a positive or negative time. The time in the "Expires" field is computed as a sum of the current time and time specified in the directive. If the modified parameter is used (0.7.0, 0.6.32) then the time is computed as a sum of the file’s modification time and the time specified in the directive. In addition, it is possible to specify a time of day using the "@" prefix (0.7.9, 0.6.34): expires @15h30m;
The contents of the "Cache-Control" field depends on the sign of the specified time: * time is negative — "Cache-Control: no-cache". * time is positive or zero — "Cache-Control: max-age=t", where t is a time specified in the directive, in seconds.
The epoch parameter sets "Expires" to the value "Thu, 01 Jan 1970 00:00:01 GMT", and "Cache-Control" to "no-cache". The max parameter sets "Expires" to the value "Thu, 31 Dec 2037 23:55:55 GMT", and "Cache-Control" to 10 years. The off parameter disables adding or modifying the "Expires" and "Cache-Control" response header fields. The last parameter value can contain variables (1.7.9): map $sent_http_content_type $expires { default off; application/pdf 42d; ~image/ max; } expires $expires;
# Cache JS CSS
location ~ .*\.(js|css)?$ {
expires 30d;
}
# Add expires Dir
location ~ ^/(images|js|css|static)/ {
expires 30d;
}
六、静态资源跨域访问
浏览器禁止跨域访问, 主要是不安全,容易出现CSRF攻击
Syntax: add_header name value [always]; Default: — Context: http, server, location, if in location
<html lang="en"> <head> <meta charset="UTF-8" /> <title>测试ajax和跨域访问</title> <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script> </head> <script type="text/javascript"> $(document).ready(function(){ $.ajax({ type: "GET", url: "http://www.myhotel.com/index.html", success: function(data) { alert("sucess!!!") }, error: function() { alert("failed!请刷新后再测试!") } }); }); </script> </html>
[root@my-node10 conf.d]# vi hotel.conf server { listen 80; server_name www.myhotel.com myhotel.com myhoteldev.com; root /application/nginx/hotel; index index.html; location ~ .*\.(html|htm)$ { add_header Access-Control-Allow-Origin http://www.myshop.com; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; } } [root@my-node10 conf.d]# nginx -s reload
添加 add_header 前后
七、 静态资源防盗链
模块: ngx_http_referer_module
首要方式:区别哪些请求是非正常用户请求
Syntax: valid_referers none | blocked | server_names | string ...; Default: — Context: server, location
启动防盗链
[root@my-node10 conf.d]# cat hotel.conf server { listen 80; server_name www.myhotel.com myhotel.com myhoteldev.com; root /application/nginx/hotel; index index.html; location ~ .*\.(html|htm)$ { add_header Access-Control-Allow-Origin http://www.myshop.com; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; } location ~ .*\.(jpg|gif|png)$ { valid_referers none blocked www.mydemo.com; if ($invalid_referer) { return 403; } root /application/nginx/images; } }
[root@my-node10 shop]# cat image.html <html> <head> <meta charset="utf-8"> <title>bug</title> </head> <body style="background-color:red;"> <img src="http://www.myhotel.com/mi.png"> </body> </html>
访问http://www.myshop.com/image.html