1

In some cases we need encrypted access to resources on our server, so how do we need to do it?

1. Modify nginx configuration

  • Modify the nginx configuration and set the resources that require encrypted access to prohibit external access

     # 资源真实存储路径 /upload 禁止外部直接访问
    location ^~ /upload {
      internal;
    }

  • When setting access to a resource that does not exist, jump to the specified php script for parsing

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

  • Configure nginx as above to implement resource encryption access instance

     # 图片真实存储路径 /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 (resource parsing script)

     <?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;

  • According to the above, confidential access to resources can be achieved, and the total implementation effect is as follows (the site domain name is: www.test.com)
    -- For example, the real address of the resource is: /upload/test.jpg
    -- Failed to visit www.test.com/upload/test.jpg
    -- Failed to access www.test.com/test.jpg
    -- Visit www.test.com/test.jpg?key=XXX success

huaweichenai
673 声望114 粉丝