Nginx – What does try_files do in this nginx configuration

nginx

I copied this config when setting up a basic Nginx / PHP-FPM webserver

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    server_name server_domain_name_or_IP;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

It works as it should, but I dont understand how the try_files in location ~ \.php$ { .... } block works when serving a request for a php file, e.g. domain.com/test.php.
I thought this line

try_files $uri =404; 

tells nginx to just go ahead and try serving the static file – i.e. append $uri to root directory, if the file exists – nginx would simply send the static file and the request would be over wouldn't it?
And therefore the fastcgi_pass wouldn't occur? but php-fpm does get it and execute the script.
Why doesn't the try_files prevent the fastcgi_pass?

Best Answer

try_files does not tell nginx to serve the static file. Reaching the closing brace in the absence of any other operation causes it to serve the static file. try_files tests for the existence of the file in the local file system and may rewrite the URL.

So try_files $uri =404; is one of a number of common tricks to overcome a particular script injection exploit by ensuring the the PHP file is a real file before sending the URL to the upstream interpreter.