1

我的 django 网站正在运行http://localhost:8000。我正在尝试将它们重定向回网站的根 url,但它无法正常工作。它一直试图将我重定向回http://localhost并丢弃该端口。我究竟做错了什么?

from django.shortcuts import redirect

class Register(View):

    def post(self, request):
        return redirect('/')

这是我的home/urls.py文件:

from home.views import (
    Index,
    Feed,
    Search,
    Profile,
    Register,
    Login,
)

urlpatterns = patterns(
    '',
    url(r'^$', Index.as_view()),
    url(r'^feed$', Feed.as_view()),
    url(r'^feed$', Feed.as_view()),
    url(r'^search$', Search.as_view()),
    url(r'^profile$', Profile.as_view()),
    url(r'^profile/(?P<id>\d+)/?(.+)$', Profile.as_view()),
    url(r'^register$', Register.as_view()),
    url(r'^login$', Login.as_view()),
    url(r'^login$', 'login', name='login'),
)

app/urls.py我有这个:

urlpatterns = patterns('',
    url(r'^favicon\.ico$', RedirectView.as_view(url="%simg/favicon.ico" % django.conf.settings.STATIC_URL)),
    url(r'^', include('home.urls')),
)

FWIW 我正在使用 vagrant 并在 vm 上运行 nginx。我让 nginx 在 vm 中的端口:80 上侦听,我将本地端口 8000 转发到 vm 上的端口:80,然后将其路由到 vm 上的端口:8000。我正在通过运行启动该站点python -B manage.py runserver 8000

4

2 回答 2

2

I see a few issues here.

  1. You should not be forwarding 8000 to anything. You should have nginx listening on port 80, and then add an upstream server which points to 127.0.0.1:8000 and launch runserver on that port. Once you have done that, your URLs should all be without a port. Forward port 80 from the vagrantfile to your host if you want the links to work. Or you could avoid all this unpleasantness by removing nginx from your setup.

  2. URL patterns don't match query strings url(r'^profile/(?P<id>\d+)/?(.+)$', Profile.as_view()), won't pass the second match as an argument. You also have duplicated patterns.

  3. Finally, consider naming your views. It is a good habit to get into. It also helps with redirection.

于 2013-08-31T19:36:58.507 回答
1

Location:-redirects使用传入Host:-header 中的主机名/端口。我认为您需要配置 nginx:发送正确的Host:-header 或修复Location:-header。

尝试这样的事情(来自http://wiki.nginx.org/LikeApachehttp://wiki.nginx.org/HttpProxyModule#proxy_redirect

server {
  listen myhost:80;
  server_name  myhost;
  location / {
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    proxy_pass http://myapp:8080;
    proxy_redirect http://myapp:8080/ http://myhost/;
  }
}
于 2013-08-31T19:55:09.693 回答