Home > database >  Nginx configuration to only forward request to php laravel server for files with prefix
Nginx configuration to only forward request to php laravel server for files with prefix

Time:10-29

I have a kubernetes deployment of a laravel app with two containers:

  • NGINX container that receives requests and either immediately returns the static files on the container (images, javascript, css..) or, if the requested file does not exist, proxy the request to the PHP container

  • PHP container running laravel

It works perfectly with the following nginx configuration:

server {
        listen 80;
        root /var/www/public;

        index index.html index.htm index.php;
        charset utf-8;

        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }

        error_page 404 /index.php;

        location ~ \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            include fastcgi_params;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|eot|ttf|woff|woff2)$ {
            expires 2d;
            add_header Cache-Control "public, no-transform";
        }
    }

Here comes the problem: I need to return some encrypted files that should be handled by laravel (to handle authorization, autentication and decryption). Those files are requested using the following endpoint:

example.com/files/decrypt/path/to/file.jpg?token=tokentovalidaterequest

Such a request generates a nginx error and 404 response (from the nginx logs, I replaced the requested path with $path):

2021/10/28 08:29:22 [error] 24#24: *1 open() "/var/www/public/files/decrypt/$path" failed (2: No such file or directory), client: 10.244.0.97, server: , request: "GET /files/decrypt/files/decrypt/$path?hash=$hash HTTP/1.1", host: "example.com"
10.244.0.97 - - [28/Oct/2021:08:29:22  0000] "GET /files/decrypt/$path?hash=$hash HTTP/1.1" 404 6622 "https://example.com" "user-agent" "ip"

The request is actually handled by php due to:

error_page 404 /index.php;

But it loses the querystring parameter and I don't want my nginx logs to be full of fake errors.

Is there a way to tell nginx "if the location starts with /files, send the request directly to php without checking if the file exists on the filesystem"?

I tried adding:

location /files {
    try_files /index.php?$query_string;
}

before the location / block, but I obtained a nginx configuration error

What is the proper way to achieve this?

CodePudding user response:

The try_files statement requires at least two parameters, see this document. You can add a fake filename as the first parameter.

For example:

try_files nonexistent /index.php?$query_string;

Alternatively, a rewrite statement would work too, and note that rewrite will automatically append the query string, see this document.

For example:

rewrite ^ /index.php last;
  • Related