0

I have managed to set up Django with Gunicorn and Nginx as to the point that it all works properly - except for one desired feature.

I would like to be able to serve /static/index.html when only accessing root (/) without changing the displayed URL in the browser. I am not sure what to use here (rewrite or alias or something else?) Here is my current nginx.conf

upstream test_server {
   server unix:/path/to/project/project.sock fail_timeout=10s;
}

server {
   listen 80;
   server_name <IP>;

   location = /favicon.ico { access_log off; log_not_found off; }

   location = / {
      alias /path/to/project/static/;  # Does not work! See comment below
   }

   location /static/ {
      alias /path/to/project/static/;  # works!
   }

   location / {
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_pass http://unix:/path/to/project/project.sock;  # communicates with Gunicorn/Django
   }
}

Comment from above: Seems to forward path index.html as a request to Django, resulting in Django complaining "Not Found: /index.html" even though Django should not even know about this. Imo Nginx should simply return /static/index.html here without involving Django.

How can I correct this (still displaying <IP>/ in the browser and not <IP>/static/index.html)?

1
server {
   # listen, server_name, etc...

   root /path/to/project;

   location = / {
       rewrite ^ /static/index.html;
   }

   location /static/ {
   }

   location / {
      # proxy ...
   }
}
  • Doesn't work. It forwards it all to Django – Sebastian Sep 2 '16 at 14:20
  • Show your real config – Alexey Ten Sep 2 '16 at 14:22
  • There is nothing else except for the real path names. With your solution I get "Not Found: /path/to/project/static/index.html" in Django – Sebastian Sep 2 '16 at 14:28
  • Are you sure your request comes to this server? – Alexey Ten Sep 2 '16 at 14:30
  • Show real config. There is nothing really often means you've just missed something… – Alexey Ten Sep 2 '16 at 14:30
0

I found the solution. It was a bit different than the one suggested by AlexeyTen:

server {
   # listen, server_name, etc...

   location = / {
       root /path/to/project;
       rewrite ^/$ /static/index.html last;
   }

   location /static/ {
       alias /path/to/project/static/;
   }

   location / {
      # proxy ...
   }
}

root outside the location blocks did not work, neither did directly including it in the rewrite URL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.