Nginx configuration example file

This is a very common setup using an upstream. It was adapted from some Capistrano recipe I found on the Internet a while ago.

  1. upstream myapp {
  2. server unix:///myapp/tmp/puma.sock;
  3. }
  4. server {
  5. listen 80;
  6. server_name myapp.com;
  7. # ~2 seconds is often enough for most folks to parse HTML/CSS and
  8. # retrieve needed images/icons/frames, connections are cheap in
  9. # nginx so increasing this is generally safe...
  10. keepalive_timeout 5;
  11. # path for static files
  12. root /myapp/public;
  13. access_log /myapp/log/nginx.access.log;
  14. error_log /myapp/log/nginx.error.log info;
  15. # this rewrites all the requests to the maintenance.html
  16. # page if it exists in the doc root. This is for capistrano's
  17. # disable web task
  18. if (-f $document_root/maintenance.html) {
  19. rewrite ^(.*)$ /maintenance.html last;
  20. break;
  21. }
  22. location / {
  23. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  24. proxy_set_header Host $http_host;
  25. # If the file exists as a static file serve it directly without
  26. # running all the other rewrite tests on it
  27. if (-f $request_filename) {
  28. break;
  29. }
  30. # check for index.html for directory index
  31. # if it's there on the filesystem then rewrite
  32. # the url to add /index.html to the end of it
  33. # and then break to send it to the next config rules.
  34. if (-f $request_filename/index.html) {
  35. rewrite (.*) $1/index.html break;
  36. }
  37. # this is the meat of the rack page caching config
  38. # it adds .html to the end of the url and then checks
  39. # the filesystem for that file. If it exists, then we
  40. # rewrite the url to have explicit .html on the end
  41. # and then send it on its way to the next config rule.
  42. # if there is no file on the fs then it sets all the
  43. # necessary headers and proxies to our upstream pumas
  44. if (-f $request_filename.html) {
  45. rewrite (.*) $1.html break;
  46. }
  47. if (!-f $request_filename) {
  48. proxy_pass http://myapp;
  49. break;
  50. }
  51. }
  52. # Now this supposedly should work as it gets the filenames with querystrings that Rails provides.
  53. # BUT there's a chance it could break the ajax calls.
  54. location ~* \.(ico|css|gif|jpe?g|png|js)(\?[0-9]+)?$ {
  55. expires max;
  56. break;
  57. }
  58. # Error pages
  59. # error_page 500 502 503 504 /500.html;
  60. location = /500.html {
  61. root /myapp/current/public;
  62. }
  63. }