2011-03-29 130 views
3

正如所描述的标题,Django不断将我的URL从/localhost/更改为/127.0.0.1:8080/,它不断让我的服务静态文件被Nginx搞乱。任何想法为什么这样做?谢谢!Django不断地将URL从http:// localhost /更改为http://127.0.0.1:8080/

/* *EDIT* */ 这里是Nginx的配置:

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; 
    } 

这里是Apache的配置文件:

<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> 
+1

你是如何建立你的网址是什么? – Jerzyk 2011-03-29 07:43:19

回答

4

EDIT2 :

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

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

我认为正在发生的事情,当你用你的httpresponseredirect,该HTTP_HOST头给它127.0.0.1:8080,因为你proxy_pass设置为。

Django's HttpResponseRedirect seems to strip off my subdomain?

的Django有它总是 适用于响应的一些方法。其中之一是 django.utils.http.fix_location_header。 这确保了重定向 响应始终包含绝对的 URI(根据HTTP规范的要求)。

+0

在我的所有链接和表单中使用相对URL。我使用Nginx将所有请求(除了静态文件)转发到Apache上,它是127.0.0.1:8080。我知道127.0.0.1与localhost相同,即使我只使用127.0.0.1,我的css文件也能正常工作。它只是每当我在我的应用程序发布形式,它重定向到8080端口这打乱了我的CSS – vol4life27 2011-03-29 05:38:44

+0

编辑您的文章,包括你的nginx/apache的confs这可能是一个设置问题 – DTing 2011-03-29 06:05:34

+0

我可能需要指出的是,它只做当我使用HttpResponseRedirect是它改变它/本地主机/到/127.0.0.1:8080/ – vol4life27 2011-03-29 23:48:38

1

有同样的问题(django重定向到浏览器与“:8080”追加)。进一步搜索后,我发现了一些nginx信息。以下固定它...

在你的nginx的配置,替换...

proxy_redirect off; 

与....

proxy_redirect http://127.0.0.1:8080/ http://127.0.0.1/; 

记得重新启动你的nginx的守护进程。这会导致nginx将从Apache返回的数据包上的8080剥离回浏览器。例如,通过apache从django重定向,http://127.0.0.1:8080/my/test/file.html将在nginx发送回客户端后变成http://127.0.0.1/my/test/file.html

现在您不必修改您的django代码。

6

如果你使用虚拟主机,你需要设置USE_X_FORWARDED_HOST = true在您的settings.py

这里的参考:Django Doc for Settings.py

USE_X_FORWARDED_HOST新在Django 1.3。1:请参阅发行 笔记

默认值:false

指定是否使用X - 转发,主机头在 偏好主机的头一个布尔值。只有在设置此标头的代理 正在使用时才能启用此功能。

下面是一些示例代码:

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 
+1

+1:这是任何正确的答案,其HTTP服务器配置正确,但其Django的服务器不是 – 2014-01-27 22:15:00

+0

这是正确的答案。 – Ilja 2015-05-06 13:53:37

相关问题