1

How can I get django to redirect all unknown urls to /

Since the react part of the project uses react-router, it changes the url in the SPA. So if I go to /options in the app, it works, but if I were to enter the url and cold load from http://example.com/options, uwsgi returns a 404.

What is the proper thing to do to prevent this?

cclloyd
  • 8,171
  • 16
  • 57
  • 104
  • static files cannot be served by whitenoise unless they are in the static directory defined by `STATIC_ROOT` (where they will all end up after you run `manage.py collectstatic`). And `collectstatic` finds all static files in each app's `static` directory + the directories you add to `STATICFILES_DIRS`. – dirkgroten Mar 18 '20 at 11:38
  • So the only way to serve top-level files like */favicon.ico* or */manifest.json* is to add them explicitly to your webserver's configuration (nginx). – dirkgroten Mar 18 '20 at 11:41
  • Redirecting unknowns urls to the root one is actually a bad idea - you should just setup a proper 404 page. – bruno desthuilliers Mar 18 '20 at 12:05
  • @brunodesthuilliers ok so I'll explicitly only redirect if it matches a pattern used in react-router by adding those urls to my `urlpatterns`. – cclloyd Mar 18 '20 at 12:09

1 Answers1

1

Regarding your second question,use 404 handler

# root_dir/views.py
from django.http.response import HttpResponseRedirect


def handler404(request, *args, **kwargs):
    return HttpResponseRedirect('/')


# root_dir/urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    ...,
    ...,
]
handler404 = 'root_dir.views.handler404'
JPG
  • 82,442
  • 19
  • 127
  • 206
  • This does make it redirect, but it loses the rest of the URL. Is there a way to make it redirect but keep the url so that react will handle it? – cclloyd Mar 18 '20 at 11:39
  • @cclloyd then in your handler, just add the url (`request.path`). – dirkgroten Mar 18 '20 at 11:43
  • You are right. To be more specific I followed the instructions here, adding it to the end of my urlpatterns (if I add it before other routes, it chooses that instead) https://stackoverflow.com/a/40826672/2228592 – cclloyd Mar 18 '20 at 11:46