angularlaravelnginx

Nginx for Angular and Laravel


Im trying to configure nginx for an angular frontend (v19) and laravel (v11) backend.
To separate BE im using a prefix of "/api/v1/" for api requests. This is prefix is not present in the backend and during development cut by the following proxy.conf.json.

Testing the configuration without the prefix works. But with the prefix an rewrite I get 404 from the nginx already because it does not seem to match the

location ~ \.php$ bloc 

anymore. I tried other rewrite syntaxes like

rewrite ^/api/v1(/.*)$ /index.php?$args
rewrite ^/api/v1(/.*)$ $1 break;
try_files $uri $uri/ /index.php?args;
Developing proxy.conf.json
{
    "/api/v1": {
        "target": "http://localhost:8000",
        "pathRewrite": { "^/api/v1": "" },
        "secure": false
    }
}

Now Im trying to start the project via docker containers and use nginx to serve backend and frontend.

Docker Nginx config

server {
    listen 8080;

    index index.php index.html;

    error_log /var/log/nginx/error.log debug;

    root /srv/api/public;

    # location / {
    location /api/v1/ { ## the match works
        rewrite ^/api/v1(/.*)$ /index.php?_url=/$1; ## looking at the resulting $uri the rewrite seems to work. But it does not match the location ~\.php$ anymore

        # try_files $uri $uri/ /index.php?$args; ## for testing without prefix - works!
    }


    location ~ \.php$ {
        fastcgi_index /index.php;
        include /etc/nginx/fastcgi_params;

        fastcgi_split_path_info       ^(.+\.php)(/.+)$;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass php:9000;
    }

    # location / { ## commented out to avoid duplicate location during testing without prefix
    #     root /srv/frontend/browser;

    #     try_files $uri $uri/ /index.html?$args;
    # }

    location ~ /\.ht {
        deny all;
    }
}
Some of the things I tried to adjust to fit my use case:

Any solutions, suggestions for a different approach or docs to read are appreciated.


Solution

  • Check this one (if it will work, I will add the explanations later):

    server {
        listen 8080;
        root /srv/frontend/browser;
    
        # angular frontend
        location / {
            try_files $uri /index.html;
        }
    
        # laravel api backend
        location ~ ^/api/v1(?<api_path>/.*) {
            include /etc/nginx/fastcgi_params;
            fastcgi_param REQUEST_URI $api_path;
            # The following should be full path to laravel index.php
            # as it seen from the php container
            fastcgi_param SCRIPT_FILENAME /srv/api/public/index.php
            fastcgi_pass php:9000;
        }
    }