26

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.

Cimbali
  • 193
  • 8
Jason
  • 363

4 Answers4

25

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;
}
Theuni
  • 968
9

I found another thing that worked for me (as I'm using gunicorn, I can't choose what to pass)

You should be able to get away with

location /cargo {
    rewrite ^/cargo(.*)$ $1 break;
    try_files $uri $uri/ /cargo/index.php?_REWRITE_COMMAND=$uri&args;
}
g3rv4
  • 191
7

For those who might be struggling to add it for micro service or API with Node JS I used the following to remove api from the url on my server:

location ^~ /api {
        rewrite ^/api(/.*)$ $1 break;
        proxy_pass    http://127.0.0.1:3001/;
    }
0

Assume your files are located under /var/www/html:

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

or with tailing slash:

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

Difference between the trailing slash can be found at NGINX, how to strip location prefix in $fastcgi_script_name

n0099
  • 125
  • 1
  • 5