use "rewrite" and "try_files" together [Nginx]

Solution 1:

You could try following approach:

location ~ ^/(?<cmd>[^/]+)/(?<scd>[^/]+) {
    try_files /index.php?cmd=$cmd&scd=$scd =404;
}

location ~ ^/(?<cmd>[^/]+)/ {
    try_files /index.php?cmd=$cmd =404;
}

location / {
    try_files $uri/ $uri.html $uri.php$is_args$args;
}

We use nginx location matching algorithm here to first check matching of URL to regular expressions and then taking appropriate action for that URL.

I am using named captures here ?<cmd> to make variable names more clear.

Also, the ?$ part at end of regular expression is removed, since it makes no difference. Both ?$ and empty match any string.