Friday, April 8, 2011

Django: How to redirect to an external URL?

[Django 1.0.2]

I have a view set up like this:

(r'^redirect/(?P<object_id>\d+)/(?P<url>.*)/$',
    'django.views.generic.simple.redirect_to',
    {'content_type': SiteType}, 'clickout'),

When I get the following URL, two different things happen on local development server and on remote mod_wsgi server:

# GET
"/redirect/2/http://www.example.com//"

# Remote server ends up (note the missing slash in the end)
"http://mydomain.com/example.com"

# Development server works as expected
"http://www.example.com/"

I have inspected the HTTP headers and it really tries the wrong URL:

"""HTTP/1.x 301 MOVED PERMANENTLY

Date: Thu, 26 Feb 2009 06:58:35 GMT

Server: Apache/2.0.52 (Red Hat) mod_wsgi/2.0 Python/2.5

Etag: "d41d8cd98f00b204e9800998ecf8427e"

Location: http://mydomain.com/example.com
Content-Type: text/html; charset=utf-8

Vary: User-Agent,Accept-Encoding

Content-Encoding: gzip

Content-Length: 20

"""

What could be the problem? How can I redirect to an external URL?

Edit

It appears embedding URLs inside URLs is not a good idea. Both apache and mod_wsgi are collapsing double slashes. (here is an explanation)

But giving the target URL as a parameter works fine:

"/redirect/2/?url=http://www.example.com/"

Thanks a lot Sean F from Webfaction support for helping me out.

From stackoverflow
  • How are you running the mod_wsgi server? I expect that because you're running the local server directly through Django no url rewriting happens. On the remote server the url gets rewritten to remove the double slash before it gets passed to your django app.

    muhuk : It loads mod_rewrite but there seems to be no conf of any rewrites. I am running on webfaction and it is a seperate apache instance.
    muhuk : Could this have anything to do with it? "WSGIScriptAlias / /path/to/my/project/myproject.wsgi"

0 comments:

Post a Comment