7

I have an Nginx configuration that is for a new PHP application that has the same functionality as another legacy PHP application, but different URLs.

I want to preserve the paths of the old application, replacing the /foo path prefix with /page and replacing the special path /foo/bar with /page/otherBar :

    # legacy support
    location ~ ^/foo/bar {
        rewrite /foo/bar /page/otherBar$1 last;
    }

    # How to rewrite all other pages starting with "/foo" ?

    # END legacy support

    location / {
        # try to serve file directly, fallback to front controller
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        proxy_read_timeout 300;
        include        fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        fastcgi_param  SCRIPT_FILENAME /usr/share/nginx/www/$fastcgi_script_name;
        fastcgi_param  PATH_INFO       $fastcgi_path_info;
        fastcgi_param  PATH_TRANSLATED $document_root$fastcgi_script_name;
        fastcgi_pass   unix:/var/run/php/php7.0-fpm.sock;
    }

This approach does not work, because $request_uri, which gets passed to REQUEST_URI in the fastcgi_params include file, still contains /foo/bar.

I've tried setting REQUEST_URI to $fastcgi_path_info but that fails for all non-rewritten URLs as it is empty then. $uri also does not work because it just contains /index.php?

Is there any variable for the third location config that contains the rewritten path?

chiborg
  • 1,083
  • 2
  • 13
  • 27

1 Answers1

11

$request_uri has the value of the original URI and $uri has the value of the final URI. You could use the set directive to save a snapshot of $uri from inside the location / block and use it later to generate the REQUEST_URI parameter.

Like this:

location / {
    set $save_uri $uri;
    try_files $uri /index.php$is_args$args;
}

location ~ ^/index\.php(/|$) {
    include  fastcgi_params;
    fastcgi_param  REQUEST_URI $save_uri;
    ...
}

See this document for more.

Richard Smith
  • 12,834
  • 2
  • 21
  • 29
  • Thank you! My original config can even be improved by adding the rewrite rules into the `location /` block (before setting the variable) – chiborg Sep 28 '16 at 16:31
  • Some time ago I used the same approach to use the modified URI. All works well, but now I encountered an issue with encoded `#` in the URL: `/foo/bar%23baz`. In PHP I get now `/foo/bar#baz`, which I don't expect. Without rewriting the `REQUEST_URI`, I get the encoded `#` as `%23`, which I expect. Is there a way to disable this decoding? – LeoRado Feb 22 '23 at 16:19