title: How to redirect 404 requests to homepage in Django single page app using Nginx?
body: <p>I have a django single page application. Currently when you visit a url on the site that doesn't exist a 404 error is displayed. However, in this case I want to redirect to the homepage of the site. I am not sure if I should how to do this with Nginx, or is there a way to do this within Django? Attached is my Nginx file below. I tried using the below setting but it did not work.</p>
  
  <pre><code>error_page 404 = @foobar;
  
  location @foobar {
    return 301 /webapps/mysite/app/templates/index.html;
  }
  
  
  upstream mysite_wsgi_server {
    # fail_timeout=0 means we always retry an upstream even if it failed
    # to return a good HTTP response (in case the Unicorn master nukes a
    # single worker for timing out).
  
    server unix:/webapps/mysite/run/gunicorn.sock fail_timeout=0;
  }
  
  server {
      listen      80;
      server_name kanjisama.com;
      rewrite     ^ https://$server_name$request_uri? permanent;
  }
  
  server {
      listen              443;
      server_name         kanjisama.com;
      ssl on;
      ssl_certificate     /etc/letsencrypt/live/kanjisama.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/kanjisama.com/privkey.pem;
      ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
  
      client_max_body_size 4G;
  
      access_log /webapps/mysite/logs/nginx_access.log;
      error_log /webapps/mysite/logs/nginx_error.log;
  
      location /static/ {
          alias   /webapps/mysite/app/static/;
      }
  
      location /media/ {
          alias   /webapps/mysite/media/;
      }
  
      location / {
          if (-f /webapps/mysite/maintenance_on.html) {
              return 503;
          }
  
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto https;
          proxy_set_header Host $host;
          proxy_redirect off;
  
          # Try to serve static files from nginx, no point in making an
          # *application* server like Unicorn/Rainbows! serve static files.
          if (!-f $request_filename) {
              proxy_pass http://mysite_wsgi_server;
              break;
          }
  
      # Error pages
      error_page 500 502 504 /500.html;
      location = /500.html {
          root /webapps/mysite/app/mysite/templates/;
      }
  
      error_page 503 /maintenance_on.html;
      location = /maintenance_on.html {
          root /webapps/mysite/;
      }
  
      error_page 404 = @foobar;
  
      location @foobar {
        return 301 /webapps/mysite/app/templates/index.html;
      }
  }
  </code></pre>