静态资源配置
- 非服务器动态运行生成的文件
- 浏览器端渲染(html、css、js)
- 图片(jpeg、gif、png)
- 视频(flv、mpeg)
- 文件(txt...)
- 静态资源服务场景--CDN
- 文件读取语法配置
sendfile on|off;
(http、server、location、if in location)
引读:--with-file-aio 异步文件读取
tcp_nopush on|off;
(http、server、location)
作用:sendfile开启的情况下,提高网络包的传输效率
tcp_nodelay on|off;
(http、server、location)
作用:Keepalive连接下,提高网络包的传输实时性
gzip on|off;
(http、server、location、if in location)
作用:压缩传输
gzip_comp_level level;
(http、server、location)
作用:压缩比,默认是1
gzip_http_version 1.0 | 1.1;
(http、server、location)
作用:http版本,默认是1.1
http_gzip_static_module --预读gzip功能
http_gunzip_module --应用支持gunzip的压缩方式
server {
listen 80;
server_name 116.62.103.228 jeson.imooc.com;
sendfile on;
access_log /var/log/nginx/log/static_access.log main;
location ~ .*.(jpg|gif|png)$ {
gzip on;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
root /opt/app/code/images;
}
location ~ .*.(txt|xml)$ {
gzip on;
gzip_http_version 1.1;
gzip_comp_level 1;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
root /opt/app/code/doc;
}
location ~ ^/download {
gzip_static on;
tcp_nopush on;
root /opt/app/code;
}
}
浏览器缓存
浏览器请求 --> 无缓存 --> 请求web服务器 --> 请求响应 --> 协商 --> 呈现
浏览器请求 --> 有缓存 --> 校验过期 --> 呈现
- 校验过期机制
- 校验是否过期:expires(http1.0)、Cache-Control(max-age)(http1.1)
- 协议中Etag头信息校验:Etag(字符串)
- Last-Modified头信息校验:Last-Modified(具体时间)
案例:
Cache-Control: max-age=0
ETag: "5ba13918-2c27"
Last-Modified: Tue, 18 Sep 2018 17:42:48 GMT
缓存配置语法:expires
expires [modified] time;
expires epoch | max |off;
(http、server、location、if in location)
作用:添加Cache-Control、Expires头,默认expires off
跨域访问
- 浏览器一般都会禁止跨域访问
- 原因是不安全,容易出现CSRF攻击
- nginx开启跨域访问设置语法
add_header name value [always];
(http、server、location、if in location)
server {
listen 80;
server_name new.test.com;
location ~ .*.(htm | html)$ {
add_header Access-Control-Allow-Origin http://www.test.com;
add_header Access-Control-Allow-Methods GET,POST.PUT.DELETE.OPTIONS;
root /opt/app/code;
}
}
防盗链
- 防止资源被盗用
- 设置思路:区别哪些请求是非正常的用户请求
- 基于http_refer防盗链配置模块
- 配置语法:
valid_referers none | blocked | server_names | string ...;
(server、location)
server {
listen 80;
server_name new.test.com;
location ~ .*.(htm | html)$ {
valid_referers none blocked 192.168.10.10 ~/baidu./;
if ($invalid_referer) {
return 403;
}
root /opt/app/code;
}
}
nginx动静分离
- 通过nginx将动态请求和静态请求进行分离。
- 作用:分离资源,减少不必要的请求消耗,减少请求延时。
- 配置案例:
http{
upstream java_api{
server 127.0.0.1:8080;
}
server {
listen 80;
server_name location;
root /opt/app/code;
location ~ .jsp$ {
proxy_pass http://java_api;
index index.html index.htm;
}
location ~ .(jpg|png|gif)$ {
expires 1h;
gzip on;
}
location / {
index index.html index.htm;
}
}
}