Django: Change base route URL
Context
We want to deploy a Django application, including its admin interface, under a specific URL prefix. For example, we want the entire site to be served under /something/
, so the admin interface would be accessible at /something/admin/
.
Solution
To achieve this, you need to modify your project's root urls.py
file. The idea is to define your application's URL patterns in a list, and then include that list under your desired path prefix.
Here is an example config/urls.py
:
from django.contrib import admin
from django.urls import path, include
# It's a good practice to define your app's specific URLs here.
# This could also be an include to another urls.py from a Django app.
app_urlpatterns = [
path('admin/', admin.site.urls),
]
# Then, you include these patterns under a common prefix.
urlpatterns = [
path('something/', include(app_urlpatterns)),
]
With this configuration, the admin interface will be available at /something/admin/
. Any other patterns in app_urlpatterns
would also be prefixed with /something/
.
A note on path()
vs re_path()
In modern Django versions (2.0 and newer), you have two functions for URL routing:
path()
: For simple, non-regular expression paths.re_path()
: For complex routing using regular expressions (similar to the olderurl()
function).
The expression path('^admin/', ...)
which you might see in older tutorials is incorrect. The ^
is a regex character. If you are using path()
, you should write path('admin/', ...)
. If you need regex matching, you should use re_path(r'^admin/', ...)
.
Example of Ingress-Nginx configuration
If you are deploying your Django application on Kubernetes, you might use an Ingress to expose it. Here is an example of an Ingress resource that routes traffic to the service.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-backend
namespace: backend
labels:
app.kubernetes.io/instance: my-backend
app.kubernetes.io/name: backend
spec:
ingressClassName: nginx
rules:
- http:
paths:
- path: /something/
pathType: Prefix
backend:
service:
name: my-backend
port:
number: 8000
Key points about this Ingress configuration:
path: /something/
combined withpathType: Prefix
will match all URLs that start with/something/
(e.g.,/something/admin/
).- If you need to use regular expressions for path matching, you would typically set
pathType: ImplementationSpecific
and add an annotation likenginx.ingress.kubernetes.io/use-regex: "true"
.