Nginx rewrite URI to remove a prefix

dockernginxphp-fpmrewriteweb-server

I have a slim application that I would like to place under a directory path on a domain. Currently I have it working fine using the default slim file provided, but I would like to put a rewrite rule.

The rewrite rule I want is that only any url prefixed with /foobar/ is accepted, with the /foobar/ stripped away before it hits slim. Here is the equivalent rewrite rule in my apache configuration which I was previously using, and worked exactly how I wanted it:

RewriteEngine On
RewriteRule ^/foobar(/.*) /foobar/public/index.php$1 [QSA,L]

The way we have it working with this rewriterule is that the $_SERVER['REQUEST_URI'] parameter remains the full "http://localhost/foobar/test", but the path (on which Slim matches the route) is just "/test", so we don't need to explicitly create a route group.

My nginx configuration looks like this at the moment:

server {
    listen 80;
    server_name  www.mysite.com mysite.com;
    root /var/www/mysite/foobar/public;

    # This is what I have tried adding, to no avail
    rewrite ^/foobar(/.*) /index.php$1 break;

    try_files $uri /index.php;

    location /index.php {
        fastcgi_connect_timeout 3s;
        fastcgi_read_timeout 10s;
        fastcgi_pass app:9000;     # "app" is a docker container

        include fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

I have been trying various rules for hours now. I'm not really sure what I'm doing, obviously misunderstanding how nginx works, and I'm sure an expert in nginx knows the right answer already. If there is anyone that can provide information as to where I am going wrong I would hugely appreciate it!

Thanks in advance!

Updated attempt:

server {
    listen 80;
    server_name  www.mysite.com mysite.com;
    root /var/www/mysite;
    index index.php;

    location ~ ^/foobar(/.*)$ {
        root /var/www/mysite/foobar/public;

        fastcgi_connect_timeout 3s;
        fastcgi_read_timeout 10s;
        fastcgi_pass app:9000;

        include fastcgi_params;
        fastcgi_param PATH_INFO $1;
        fastcgi_param SCRIPT_FILENAME $document_root/index.php;
    }
}

Best Answer

You are right, nginx has different logic with redirects.

This approach might work for you. However, I haven't used nginx with software that uses patterns like this, so I'm not sure if this will work. Also, this might not be the optimal way of performing this.

location ~ ^/foobar(/.*)$ {
    fastcgi_connect_timeout 3s;
    fastcgi_read_timeout 10s;
    fastcgi_pass app:9000;     # "app" is a docker container

    include fastcgi_params;
    fastcgi_param PATH_INFO $1;
    fastcgi_param SCRIPT_FILENAME $document_root/index.php;
}