Nginx Configuration – How to Remove Location Block from $uri

nginx

I have a rewrite in my ngix conf file that works properly except it seems to include the location block as part of the $uri variable. I only want the path after the location block. My current config code is:

location /cargo {
    try_files $uri $uri/ /cargo/index.php?_REWRITE_COMMAND=$uri&args;
}

Using an example url of http://localhost/cargo/testpage the redirect works, however the value of the "_REWRITE_COMMAND" parameter received by my php file is "/cargo/testpage". I need to strip off the location block and just have "testpage" as the $uri

I am pretty sure there is a regex syntax to split the $uri and assign it to a new variable using $1 $2 etc, but I can't find any example to do just a variable assignment using a regex that is not part of a rewrite statement. I've been looking and trying for hours and I just can't seem to get past this last step.

I also know I could just strip this out on the application code, but the reason I want to try to fix it in the nginx conf is for compatibility reasons as it also runs on Apache. I also should say that I have figured out a really hacky way to do it, but it involves an "if" statement to check for file existance and the documentation specifically says not to do it that way.

Best Answer

Looking around I would guess that using a regexp location with captures is the easiest. Adapting your example I end up with:

location ~ ^/cargo(.*) {
    try_files $1 $1/ /cargo/index.php?_REWRITE_COMMAND=$1&args;
}
Related Topic