4

If my (Rails) application is down or undergoing database maintenance or whatever, I'd like to specify at the nginx level to serve a static page. So every URL like http://example.com/* should serve a static html file, like /var/www/example/foo.html.

Trying to specify that in my nginx config is giving me fits and infinite loops and whatnot.

I'm trying things like

location / {
  root /var/www/example;
  index foo.html;
  rewrite ^/.+$ foo.html;
}

How would you get every URL on your domain to serve a single static file?

dreeves
  • 238
  • 1
  • 3
  • 9

4 Answers4

5

I am not 100% sure but if the Rails server fails there is an error 500. Maybe you could use the error_page directive like

error_page 500 /staticpage.html
Christopher Perrin
  • 4,811
  • 19
  • 33
  • Ah, that's smart, and I should do that too, but I'd still like to get nginx to cooperate with a catchall rewrite. The reason is that I may need to flip that on when the Rails app isn't actually down yet but we're migrating the database or something. Thanks for pointing out error_page though! – dreeves Jun 22 '12 at 01:49
4

Add two locations like this:

location = /foo.htm {
  root /var/www/example;
  index foo.html;
}

location / {
  rewrite ^/.+$ /foo.htm;
}
Christopher Perrin
  • 4,811
  • 19
  • 33
3

Use named location, it's doesn't change URI during redirect.

This snippet processes "rails is down" situation.

error_page 504 @rubydown; # 504 - gateway timeout

location @rubydown {
    internal;
    root /var/www;
    rewrite ^ /504.html break;
}

For maintaince notification you can use something similar in root location ...

location / {
    root /var/www;
    try_files /maintaince.html @rails;
}

location @rails {
    internal;
    proxy_pass http://rails.backend;
    # blablabla proxy_pass setting for Rails
}

Create file /var/www/maintaince.html.tmpl, write desired text. And before maintaince work create simlink similar ln -s /var/www/maintaince.html.tmpl /var/www/maintaince.html or just rename file. When maintaince work has done, remove simlink or rename file back.

cadmi
  • 7,308
  • 1
  • 17
  • 23
  • That's clever and convenient! But it seems like it entails a tiny performance hit during normal operation, checking for the maintenance.html page on every pageview. Does that sound correct or is there clever caching or something that makes it really not an issue at all? – dreeves Jul 16 '12 at 03:57
  • Sorry for "necro" comment, I did not notice this issue in July. Not issue at all, don't worry. This "right way" for such use case, recommended by Igor Sysoev (nginx author) by himself at nginx's russian maillist. – cadmi Sep 20 '12 at 09:06
2

The following should redirect all the requests to /var/www/example/foo.html.

location / {
  root /var/www/example;
  index foo.html;
  # In the following try_files directive, the request will never reach =404.
  try_files /foo.html =404;
}
Pothi Kalimuthu
  • 6,117
  • 2
  • 26
  • 38