The 504 is sent by the server if you reach the max execution time (in Apache it defaults to 30 seconds). However the script still runs in the background -- it just stops sending data to the client. If you anticipate your script running for more than the max execution time and want to see the data it returns, you should consider either upping the max execution time setting on your server or running the script elsewhere and reporting back to the browser via a socket connection or interval polling.
On another note, why are you using nginx AND apache? Or do you mean that it does the same thing on both?