Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mathewparet's avatar

Laravel NGINX config - deny access to particular files in public directory

How do I restrict user's from downloading any file but a specific one in the public directory when using NGINX?

My Nginx Config:

server {
        root /var/www/redacted/public;
        index index.php index.html index.htm;
        server_name lib.redacted.com;

	location ~ \.db$ {
		return 404;
		deny all;
        }

        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        }

        listen 192.168.1.122:443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/redacted/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/redacted/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = lib.redacted.com) {
        return 301 https://$host:443$request_uri;
    } # managed by Certbot

    listen 192.168.1.122:80;
    server_name lib.redacted.com;
    return 404; # managed by Certbot

}

I have some files in /var/www/redacted/public/covers/*/* which I need to access to the outside world. However I need to make sure any *.db file present in these folders are not downloaded.

However, with the above config, it people can still download something,db from /var/www/redacted/public/covers/*/*

How do I restrict that?

0 likes
4 replies
MohamedTammam's avatar

Easiest way is not adding *.db files in the public directory nor public storage.

mathewparet's avatar

I get that, but I can't do it. I am mapping a subfolder in public to a different path on the server. That folder is managed by another application, so I can't avoid .db file not being there. I need to figure out a way to avoid downloading.

Alternative is to pass the route through laravel router and let laravel stream download the file to the browser. But I don't want to unnecessarily hog PHP memory just for that purpose.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Seems you have a space in there?

location ~\.db$ {
		return 404;
		deny all;
        }

And remember to reload/restart nginx

Please or to participate in this conversation.