Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django not taking script name header from nginx

Tags:

nginx

django

I am using Django 1.8 by the way.

I am trying to deploy multiple Django app at with same domain/subdomain but different URLs so I am using SCRIPT_NAME header.

My Nginx config:

location /myapp/ {
    proxy_pass http://127.0.0.1:8000/;
    proxy_set_header SCRIPT_NAME /myapp;
}

Site is loading with this conf but the request. META['SCRIPT_NAME'] is empty as well as when I hover any links, they are showing without 'myapp' in the URL.

Any help?

like image 645
user1305989 Avatar asked Oct 22 '25 14:10

user1305989


1 Answers

I didn't find the answer to this in all my searching, so here it is:

  1. This is only properly implemented in Django 3.1.6, so 1.8 won't work.
  2. proxy_pass http://127.0.0.1:8000/ is wrong, you need proxy_pass http://127.0.0.1:8000 (without the trailing backslash) in order to keep /myapp at the start of the URL path. Django expects its requests to start with the value of the SCRIPT_NAME header, and strips it off before your apps see it. Django will return an error for any URL that doesn't start like this.
  3. If your settings.py defines STATIC_URL as an absolute path like /static/, Django will not prepend it with your script name. Use a relative path like static/.
  4. If there are any other proxies in between, make sure they are not dropping the STATIC_FILES header. For example, if you have another nginx in between then you need to make sure that your server block contains the line underscores_in_headers on;.
  5. settings like LOGIN_REDIRECT_URL are not prepended (and you cannot use the relative path trick as this does something different), so you can fudge this with a line: proxy_redirect / /myapp/;, but then most redirects are prepended, so you also need a line before that: proxy_redirect /myapp/ /myapp/;. This technique will not work if /myapp/myapp is actually a valid path, of course.
  6. If you want to serve the static files statically, remember to include a location block for that.

So your nginx block should look a bit like this:

location /myapp/ {
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header SCRIPT_NAME /myapp;
    proxy_redirect /myapp/ /myapp/;
    proxy_redirect / /myapp/;
    location /myapp/static/ {
        root /var/www; # files are deployed to /var/www/myapp/static
    }
}

and in settings.py:

STATIC_URL=`static/`

and in requirements.txt:

Django==3.1.6

What a nightmare. Does anybody have any better ideas?

like image 143
Tim Band Avatar answered Oct 24 '25 08:10

Tim Band



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!