在有些状况下咱们须要对咱们服务器上的资源进行加密拜访,那么咱们须要如何来实现呢?

1. 批改nginx配置

  • 批改nginx配置,将须要加密拜访的资源设置为禁止内部拜访

    # 资源实在存储门路 /upload 禁止内部间接拜访location ^~ /upload {  internal;}

  • 设置拜访不存在资源时,跳转到指定的php脚本进行解析

    # 如果文件不存在,则rewrite到PHP脚本文件进行解决if (!-f $request_filename) {  rewrite ^/.*$ /attachment.php;}

  • 依据如上配置nginx实现资源加密拜访实例

    # 图片实在存储门路 /upload 禁止内部间接拜访location ^~ /upload/school {  internal;}location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)${  # 如果文件不存在,则rewrite到PHP脚本文件进行解决  if (!-f $request_filename) {      rewrite ^/.*$ /attachment.php;  }  expires      30d;  error_log /dev/null;  access_log /dev/null; }

    2. attachment.php(资源解析脚本)

    <?php// key参数为校验参数,有该参数即可通过验证,否则不通过if (!isset($_GET['key'])) {  exit('get img failed!');}//key验证逻辑$imagePath = $_SERVER['DOCUMENT_ROOT'] . '/upload/';$image = $_SERVER['REQUEST_URI'];// 拼接图片实在全门路$fullPath = $imagePath . $image;// 获取图片mime信息 设置Content-type头$mime = getimagesize($fullPath)['mime'];header("Content-Type: $mime");// 设置sendfile头部,让nginx跳转到download下查找对应图片 相当于交给nginx进行后续解决header("X-Accel-Redirect: /upload/$image");die;

  • 依据如上就能够实现资源秘密拜访,最总实现成果如下(站点域名为:www.test.com)
    -- 例如资源实在地址为:/upload/test.jpg
    -- 拜访 www.test.com/upload/test.jpg 失败
    -- 拜访 www.test.com/test.jpg 失败
    -- 拜访 www.test.com/test.jpg?key=XXX 胜利