Nginx How to rewrite all urls except few having specified extensions

mod-rewritenginxrewriteweb-server

i am trying to convert rewrite rules from .htaccess files to nginx config. as a part of moving site to NGINX webserver.

here are rewrite rules from .htaccess file

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !\.php$
RewriteCond %{REQUEST_URI} !\.gif$
RewriteCond %{REQUEST_URI} !\.jp?g$
RewriteCond %{REQUEST_URI} !\.png$
RewriteCond %{REQUEST_URI} !\.css$
RewriteCond %{REQUEST_URI} !\.js$
RewriteCond %{REQUEST_URI} !\.html$
RewriteCond %{REQUEST_URI} !\.xhtml$
RewriteCond %{REQUEST_URI} !\.htm$
RewriteCond %{REQUEST_URI} !\.ico$

RewriteRule (.*) index.php [L]
RewriteRule (.*).html index.php [L]

my current nginx config.

server {
    listen       80;
    server_name  example.com;

    root   /usr/share/nginx/html;

    location / {
        index  index.php index.html index.htm;
    }

    location ~ \.(php)$ {
        try_files $uri =404;
        root           /usr/share/nginx/html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location !~* .(css|js|html|htm|xhtml|php|png|gif|ico|jpg|jpeg)$ {
      # Matches requests ending in png, gif, ico, jpg or jpeg. 
        rewrite ^(.*)$ /index.php break;
        rewrite (.*).html /index.php break;
    }

}

home page is working but internal site links are giving 404.

so far i have tried many rewrite rules like these.

if ( $uri  ~ ^/(?!(\.css|\.js|\.html|\.htm|\.xhtml|\.php|\.png|\.gif|\.ico|\.jpg|\.jpeg))) { 
    rewrite ^/(.*)$ /index.php break;
}

but sometimes, internal link works, while redirecting all static files like .css,.js to home page,
and sometime i can't access /administrator/ of my site, it redirects to the home page.

how can i replicate the .htaccess rewrite rules to nginx ?

Best Answer

To me this looks like a standard front-controller pattern. In nginx, it is implemented like this:

server {
    listen       80;
    server_name  example.com;

    root   /usr/share/nginx/html;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.(php)$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

The logic here is that it first tries to find if the requested resource exists as a file or a directory. If it exists, it is returned to the client. Otherwise the request is passed to the PHP script, which then determines the content to be returned to the client.