Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I configure Nginx to route a specific request pattern to a specific php-fpm upstream hosting a Symfony application?

I'm developing an application composed of 3 microservices. Each microservice is a Symfony 4 application.

To route all my request made to this application I'm using Nginx.

There are, for now, three url patterns, one for each microservice. One of them is the ^/auth pattern which allow the access to the authentication API through the php-fpm upstream.

I've tried many things but for now this is the closest Nginx configuration I have from my objective.

server {

    listen 80;
    server_name app.local;
    root /app;

    # location directive for the authentication API
    location ~ ^/auth/ {

        root /app/public;

        fastcgi_pass auth_api_upstream;
        fastcgi_split_path_info ^(/auth)(/.*)$;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        fastcgi_param SCRIPT_FILENAME $realpath_root/index.php$fastcgi_path_info;

        include fastcgi_params;
    }

    # ....

    # return 404 if other location do not match
    location / {
        return 404;
    }
}

With this configuration, this is what append :

  • I make a request : GET /auth/publicKey
  • Nginx handle the request : GET /auth/publicKey and forward it to my application through the upstream
  • The Symfony application handle the request : GET /auth instead of GET /publicKey (my objective)

While Nginx is handling the request :

  • $realpath_root = '/app/public' : Where the Symfony entrypoint is on the php-fpm host
  • $fastcgi_path_info = '/publicKey' : A valid route url in the Symfony application

So my questions are :

  • Why is my application handling a GET /auth request when the request previously handled by Nginx is GET /auth/publicKey ?
  • And therefor, how to fix it ?

Thank you for your answers :)

like image 902
hunomina Avatar asked Oct 26 '25 13:10

hunomina


1 Answers

Try to move the include fastcgi_params; line upward

something like this:

server {

    listen 80;
    server_name app.local;
    root /app;

    location ~ ^/auth/ {

        root /app/public;

        set $app_entrypoint /index.php;

        fastcgi_pass auth_api_upstream;
        fastcgi_split_path_info ^(/auth)(/.*)$;
        include fastcgi_params;

        fastcgi_param DOCUMENT_ROOT $document_root;
        fastcgi_param DOCUMENT_URI $app_entrypoint;

        fastcgi_param REQUEST_URI $fastcgi_path_info;

        fastcgi_param SCRIPT_NAME $app_entrypoint;
        fastcgi_param SCRIPT_FILENAME $document_root$app_entrypoint;

    }

    # return 404 if other location do not match
    location / {
        return 404;
    }
}
like image 171
SBNTT Avatar answered Oct 28 '25 03:10

SBNTT