how to remove location block from $uri in nginx configuration?

Posted by Jason on Server Fault See other posts from Server Fault or by Jason
Published on 2012-12-06T18:47:12Z Indexed on 2012/12/06 23:05 UTC
Read the original article Hit count: 123

Filed under:

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.

--> UPDATE: ANSWERED BY theuni:

The regex goes in the location block definition. one note of caution is that php handler location needs to be ABOVE this location, otherwise you will get a server error because it goes into an infinite redirect loop

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

© Server Fault or respective owner

Related posts about nginx