nginx with php and rewrite rule
===

I'd like to set my nginx server with php, and a simple rewrite rule. I tried to make a rewrite rule, that any urls which points to non existing file or directory, rewrites to /index.php?q=<url>. I created this nginx.conf:

    events {
    }
    
    http {
      include fastcgi.conf;
      server {
        listen          80;
        server_name     www.example.com;
        index           index.php;
        root            /var/www/html/www.example.com;
        location / {
          index     index.php;
          if (!-f $request_filename) {
            rewrite ^/(.*)$ /index.php?q=$1 last;
          }
          if (!-d $request_filename) {
            rewrite ^/(.*)$ /index.php?r=$1 last;
          }
        }
        location ~ \.php {
          try_files $uri =404;
          fastcgi_pass 127.0.0.1:9999;
        }
      }
    }

This works, but not in every case. It perfectly rewrites utls like tihs:

http://www.example.com/111/222/333

But two case not works as i want:

http://www.example.com/111/222/333.php

drops 404 error.

And www.example.com/forum/index.php exists, so the www.example.com/forum/index.php executes index.php in forum directory, this is fine. But www.example.com/forum url rewrites to /index.php, not execute index.php in forum directory as i want.

How can i solve this two problem?

Thank you!
