nginx - build your letitbit

    There was a desire to make a service similar to in a single country on the outskirts of Europe.
    It was required:
    • allow upload / upload of large files;
    • Do not allow the reproduction of direct links to files;
    • limit the number of simultaneously downloaded files.

    For implementation, they chose NGINX in conjunction with PHP through fastcgi.
    In NGINX added:
    1. gorgeous Nginx upload module , which avoids multiple copying of the downloaded file in the NGINX-PHP path. In addition, with a little refinement, it is possible to download directly to the desired folder, which allows you to use simple renaming instead of copying to PHP
    2. the required patch for the secure_link module, which allows you to make secure links valid for a limited time

    PHP took the most common and launched through spawn-fcgi .
    They put a little servochka, stuffed there 12 pieces of terabyte disks.
    The programmer wrote the PHP code, and Maris Ruskulis came up with the following trick with rewrite for NGINX, which avoids access to PHP when downloading the file.
    As a result, the NGINX configuration looked something like this: The remarkable thing in this config is the fact that when downloading a file using the generated time-sensitive anti-spoof link (the check is performed by secure_link) PHP is not called with the subsequent X-Accel-Redirect .
    http {
    limit_zone regular $zonekey 10m;
    limit_zone premium $zonekey 10m;
    server {
    root /www/oursiteishere;
    location / { try_files $uri @files; }
    location ~ \.php$ { try_files $uri @files; fastcgi_stuff_here; }
    location @files { rewrite ^(.*)$ /index.php?$1 last; }
    location /storage/ { root /storages/; internal; }
    # Location for regular users
    location ~ /download/.+/(.+)/0/.+/.*/(.+)$ {
    set $fname $2;
    set $username $1;
    set $zonekey "$binary_remote_addr $username";
    limit_conn regular 1;
    limit_rate '100k';
    secure_link_secret megasecret;
    secure_link_ttl on;
    if ($secure_link = "") { return 403; }
    add_header Content-Disposition "attachment; filename*=UTF-8''$fname";
    rewrite ^/download/([a-f0-9]+)/([\.~0-9a-zA-Z_]+)/([01])/([0-9]+)/(.+)/.+$ /storage/$4/$5 break;
    # Location for premium users
    # Location for upload using upload module

    Perhaps this solution imposes a restriction on the presence of logic before directly uploading the file, but nevertheless, in my opinion, it is a rather original trick that allows saving a little on fastcgi.

    Also popular now: