How to change REQUEST_URI passed to FastCGI script?

My Caddyfile contains this:

handle /api/* {
    root * /var/www
    rewrite * /api.php
    php_fastcgi unix//run/php/php7.4-fpm.sock

If I request then my script is called with:

REQUEST_URI     => /api/test
SCRIPT_FILENAME => /var/www/api.php

My question is: Is there any way I can strip the /api-prefix, so that the script does not have to know about it?

I tried the following:

handle /api/* {
    uri strip_prefix /api
    reverse_proxy unix//run/php/php7.4-fpm.sock {
        transport fastcgi {
            env SCRIPT_FILENAME /var/www/api.php

But even with that config, I still see REQUEST_URI set to /api/test, although it then sets PATH_INFO and PATH_TRANSLATED to /test.

REQUEST_URI will always be the original path of the request. You should be using PATH_INFO instead in your PHP script if you want the path as rewritten by the server.

You can replace this with handle_path /api/*, which is a shortcut for handle + uri strip_prefix.

Thanks, based on this, I assume my Caddyfile should actually be like this:

handle_path /api/* {
    rewrite * /api.php/{path}
    php_fastcgi unix//run/php/php7.4-fpm.sock

(and I will have to update routing library to use a URI instance constructed from PATH_INFO instead of the default).

Thanks, I actaully saw handle_path in the page about reverse_proxy (last example), but the generated link is to handle, so I assumed it was a typo.

Presumably the script that auto-links directives in the examples does not ensure it finds longest match.

Yeah, probably.

See the docs here:

The URI which was given in order to access this page; for instance, ‘/index.html’.

Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL, then $_SERVER[‘PATH_INFO’] would contain /some/stuff.

Yeah this is a bug in the syntax highlighter that I wrote. I implemented the syntax highlighting lexer before handle_path existed and I haven’t spent the time going back to fix it yet. Sorry about the confusion there.

1 Like

This topic was automatically closed after 30 days. New replies are no longer allowed.