How to host a Django project in a subpath?

后端 未结 2 445
不知归路
不知归路 2021-01-12 13:25

I am building an API with Django REST framework which is served via Gunicorn and Nginx. The project \"exampleproject\" has to run at a subpath such as: https://100.100.100.1

2条回答
  •  情书的邮戳
    2021-01-12 14:13

    Just remove the trailing slash from the proxy pass URL, like this:

    proxy_pass http://localhost:8007;
    

    If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, then keeping the /exampleproject/ part.

    See: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

    Then you will need to configure Django to understand the URLs under /exampleproject/.

    First, you can prepend the subpath to all URLs by updating the urls.py file like this:

    urlpatterns = [url(r'^exampleproject/', include(urlpatterns))]
    

    And, in case you are serving statics and media just update in the settings:

    MEDIA_URL = '/exampleproject/media/'
    STATIC_URL = '/exampleproject/static/'
    

    Of course you can create a custom setting to replicate this or to make the app work without a subpath as well, I believe this is a better solution than FORCE_SCRIPT_NAME because in that case I found we need to update the Django URLs anyways.

提交回复
热议问题