首页 > 系统相关 >Nginx基础 - 04静态资源

Nginx基础 - 04静态资源

时间:2023-03-11 13:15:41浏览次数:39  
标签:http 04 静态 server Nginx location time gzip off

   

一、静态资源类型

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

     

 

 

 

 

标签:http,04,静态,server,Nginx,location,time,gzip,off
From: https://www.cnblogs.com/kingdomer/p/13936224.html

相关文章

  • Nginx基础 - 03基本配置
     一、Nginx配置文件结构Nginx主配置文件/etc/nginx/nginx.conf是一个纯文本类型的文件。整个配置文件是以区块的形式组织的。一般,每个区块以一对大括号{}来表示开始于......
  • ubuntu22.04 安装新版 linuxqq
    1.浏览器打开网址https://im.qq.com/linuxqq/index.shtml,并下载X64deb版的包2.到达Downloads目录下(你deb文件的默认下载位置):cdDownloads3.运行命令:sudodp......
  • Nginx 负载均衡反向代理 Windows安装部署教程
     一、Nginx简介   Nginx(enginex)是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。它也是一种轻量级的Web服务器,可以作为独立的服务器部署网站......
  • day05-功能实现04
    功能实现04后端:https://github.com/liyuelian/furniture-back-end.git前端:https://github.com/liyuelian/furniture-front-end.git9.功能09-添加家居表单前端校验9.1......
  • linux基础day04:bash初识02
    bash初识02shell的基本用法命令[-options]argumentscommand-选项参数(动作对象)目录名/路径命令(必须在顶格)格式:#命令空格[选项]空格[......
  • Ubuntu 20.04 分区方案
     说明:固态硬盘是/dev/nvme0n1,分为4个分区:swap分区:32G,因为我的内存是32G(主分区)/usr:很多应用程序和文件都放在这个目录下,类似于windows下的programfiles目录,我分......
  • 04 文件的高级操作:控制文件指针的移动
    """@作者:egon老湿@微信:18611453110@专栏:https://zhuanlan.zhihu.com/c_1189883314197168128"""#指针移动的单位都是以bytes/字节为单位#只有一种情况特殊:#t......
  • Nginx 入门
    Nginx是一款高性能、高可靠性的Web服务器,它能够处理大量并发请求,并且可以作为反向代理、负载均衡器、HTTP缓存和安全性代理等多种用途。下面是一个简单的Nginx......
  • 树莓派烧录ubuntu18.04.5
    准备工作:树莓派4B一个,内存不小于16G的TF卡一个,树莓派的充电线一个,笔记本电脑一台,网线一根,读卡器一个1、格式化TF卡建议选择16G以上的TF卡,下载格式化工具选择要格式化的T......
  • 不支持设置运行目录主机thinkphp伪静态使用方法.htaccess
    不支持设置运行目录主机thinkphp伪静态使用方法.htaccess资源宝分享:​​www.httple.net​​<IfModulemod_rewrite.c>RewriteEngineonRewriteBase/RewriteCond%{REQUEST_......