Nginx安全链接模块不适用于php文件,但适用于静态文件


Nginx secure link module not working with php files but working on static files

我正在使用 http://nginx.org/en/docs/http/ngx_http_secure_link_module.html Nginx安全链接模块来保护静态文件下载。它适用于静态文件。

但是当我尝试使用 php 文件实现这一点时,它不起作用。基本上我通过ajax请求使用它,例如

http://www.example.com/dev/serve.php?h=hash&t=timestamp

当我在下面检查时,尽管它没有哈希和时间戳,但它不受任何限制地工作:

http://www.example.com/dev/serve.php

对于静态文件,它正常工作,即当访问任何没有哈希和时间戳的图像时,它返回指定的错误请求响应:

http://www.example.com/dev/image.png

服务器配置:

#
# The default server
#
server {
    listen       80;
    server_name  www.example.com;
    location / {
        root   /box;
        index  index.php index.html index.htm;
    }
    error_page  404              /404.html;
    location = /404.html {
        root   /box;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    location ~ '.php$ {
        root   /box;
        try_files $uri =404;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
    location /dev/ {
        root   /box;
        secure_link $arg_h,$arg_s;
        secure_link_md5 "secret$uri$secure_link_expires$remote_addr";
        if ($secure_link = "") {
            return 403;
        }
        if ($secure_link = "0") {
            return 410;
        }
    }
}

我的问题:

  1. 它不适用于像php这样的动态文件吗?
  2. 如果适用,那么如何实施它?

过了一会儿,我找到了解决方案:

#
# The default server
#
server {
    listen       80;
    server_name  www.example.com;
    location / {
        root   /box;
        index  index.php index.html index.htm;
    }
    error_page  404              /404.html;
    location = /404.html {
        root   /box;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    location ~ '.php$ {
        root   /box;
        secure_link $arg_h,$arg_s;
        secure_link_md5 "secret$uri$secure_link_expires$remote_addr";
        if ($secure_link = "") {
            return 403;
        }
        if ($secure_link = "0") {
            return 410;
        }
        try_files $uri =404;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

请注意,该解决方案适用于 php 文件,只需进行少量修改,它也适用于其他文件。