Django管理页面在使用Kong网关时无法打开

0 投票
1 回答
52 浏览
提问于 2025-04-12 17:54

我在用Kong网关让我的Django项目可以通过 localhost/python 访问。我可以看到Django的启动页面,但当我尝试打开 localhost/python/admin 时,它会重定向到 localhost/admin/login/?next=/admin/,这就不再是我的Django项目了。我的项目只是通过 python -m startproject 创建的文件,并连接了数据库。
我该怎么做才能解决这个问题呢?谢谢!

这是Kong服务和路由的样子:

{
  "enabled": true,
  "tls_verify": null,
  "tls_verify_depth": null,
  "port": 3000,
  "protocol": "http",
  "path": null,
  "client_certificate": null,
  "write_timeout": 60000,
  "connect_timeout": 60000,
  "retries": 5,
  "read_timeout": 60000,
  "id": "8da72803-ffea-4424-a568-31faa3782a6d",
  "name": "python-service",
  "host": "python-service",
  "updated_at": 1711390446,
  "created_at": 1711390446,
  "tags": null,
  "ca_certificates": null
}

路由:

{
  "next": null,
  "data": [
    {
      "strip_path": true,
      "regex_priority": 0,
      "methods": null,
      "request_buffering": true,
      "response_buffering": true,
      "protocols": [
        "http",
        "https"
      ],
      "service": {
        "id": "8da72803-ffea-4424-a568-31faa3782a6d"
      },
      "https_redirect_status_code": 426,
      "tags": null,
      "paths": [
        "/python"
      ],
      "headers": null,
      "id": "2c1fb24a-21dd-42f5-9784-a3bf95c6f7dc",
      "path_handling": "v0",
      "created_at": 1711390464,
      "updated_at": 1711390464,
      "name": null,
      "snis": null,
      "sources": null,
      "hosts": null,
      "preserve_host": false,
      "destinations": null
    }
  ]
}

1 个回答

0

你的问题出在Kong路由设置中的 strip_path: true 这个值上。

当这个值设置为 true 时,Kong会在把请求转发到你的上游服务(在这个例子中是Django)之前,从URL中去掉与路由匹配的路径。这就是为什么当你尝试访问 localhost/python/admin 时,Kong会去掉'/python',只留下'/admin',而'/admin'在你的Django项目中并不存在。

所以,你应该把 strip_path 的值改成 false,像这样:

{
  "next": null,
  "data": [
    {
      "strip_path": false,
      ...
      "paths": [
        "/python"
      ],
      ...
    }
  ]
}

strip_path 设置为 false 时,最初对 localhost/python/admin 的请求会被转发到你的Django项目,路径会保持为 /python/admin,这样Django就能正确处理路由了。

做完这个修改后,记得重新加载你的Kong配置,以便应用这些更改。

请注意,这也意味着你需要调整Django项目的URL配置,以处理路径中多出的'/python',因为Django现在会把它视为路径的一部分。所以确保你的Django URLs设置正确。

撰写回答