Django Rest Framework 反向关系在代理后面中断

Django Rest Framework Reverse Relationship Breaks When Behind Proxy

我正在尝试提供一个 django webapp,它使用 gunicorn 和 httpd 作为代理,它也提供静态内容。一切正常,除了 django rest framework searchable API root(应用程序 API 的入口点)没有提供正确的 url。 url 用于本地主机和 gunicorn 服务的端口,而不是机器的 ip 地址或其主机名。这是应用程序的 httpd conf 文件:

<VirtualHost *:80>
    DocumentRoot /opt/example
    ProxyPass /static/ !
    Alias /static/ /var/www/html/static/
    ProxyPass / http://localhost:8000/
    ProxyPassReverse / http://localhost:8000/
 </VirtualHost>

Gunicorn 在端口 8000 上的本地主机上提供服务。

这是 api 的视图:

@api_view(('GET',))
def api_root(request, format=None):
    return Response({
        'activity': reverse('activity-list', request=request, format=format)
        'test' : reverse('test-list', request=request, format=format)
    })

当点击 api 根页面时,这是我得到的响应:

HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, HEAD, OPTIONS

{
    "activity": "http://localhost:8000/activity/",
    "tests": "http://localhost:8000/test/",
}

您的 httpd.conf 中有错别字 httpd

该行应该是:

ProxyPassReverse / http://localhost:8000/

我有一个类似的设置,它似乎工作得很好。

确保您的 settings.py 中有 USE_X_FORWARDED_HOST = True,因为它默认为 False

更多信息here