Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django keeps changing URL from http://localhost/ to http://127.0.0.1:8080/

As the title described, Django keeps changing my URL from /localhost/ to /127.0.0.1:8080/ which keeps messing up my serving static files by Nginx. Any ideas why its doing this? Thanks!

/**EDIT**/ Here is the Nginx configuration:

server {

    listen   80; ## listen for ipv4
    listen   [::]:80 default ipv6only=on; ## listen for ipv6

    server_name  localhost;

    access_log  /var/log/nginx/localhost.access.log;

    location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
    {
            root   /srv/www/testing;
    }

    location / {
            proxy_pass         http://127.0.0.1:8080/;
            proxy_redirect     off;
    }

    location /doc {
        root   /usr/share;
        autoindex on;
        allow 127.0.0.1;
        deny all;
    }

    location /images {
        root   /usr/share;
        autoindex on;
    }

Here is Apache config file:

<VirtualHost *:8080>

    ServerName testing
    DocumentRoot /srv/www/testing

    <Directory /srv/www/testing>
        Order allow,deny
        Allow from all
    </Directory>

    WSGIScriptAlias / /srv/www/testing/apache/django.wsgi

</VirtualHost>
like image 620
vt-cwalker Avatar asked Dec 17 '22 15:12

vt-cwalker


2 Answers

If you're using VirtualHost, you need to set USE_X_FORWARDED_HOST = True in your settings.py

Here's the reference: Django Doc for Settings.py

USE_X_FORWARDED_HOST New in Django 1.3.1: Please, see the release notes

Default: False

A boolean that specifies whether to use the X-Forwarded-Host header in preference to the Host header. This should only be enabled if a proxy which sets this header is in use.

Here's some example code:

import os, socket
PROJECT_DIR = os.path.dirname(__file__)

on_production_server = True if socket.gethostname() == 'your.productionserver.com' else False

DEBUG = True if not on_production_server else False
TEMPLATE_DEBUG = DEBUG

USE_X_FORWARDED_HOST = True if not on_production_server else False
like image 194
Lionel Avatar answered Dec 28 '22 07:12

Lionel


edit2:

http://wiki.nginx.org/HttpProxyModule#proxy_redirect

http://wiki.nginx.org/HttpProxyModule#proxy_pass

What I think is happening is when you use your httpresponseredirect, the HTTP_HOST header is giving it the 127.0.0.1:8080, because of your proxy_pass setting.

Django's HttpResponseRedirect seems to strip off my subdomain?

Django has some methods it always applies to a response. One of these is django.utils.http.fix_location_header. This ensures that a redirection response always contains an absolute URI (as required by HTTP spec).

like image 37
dting Avatar answered Dec 28 '22 06:12

dting