4

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?

1 Answer 1

6

$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.

1
  • 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, 2016 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.