Search code examples
djangohttp-redirecturl-pattern

Django: Redirect if the link doesn't match urlpatterns


How do I make django to redirect from www.example.com to www.example.com/home ?

Below you can see my urlpaterns and I'm using url(r'', RedirectView.as_view(pattern_name='home', permanent=False))to redirect to my /home page but when it detects a link without / at the end it redirects me to the /home page.

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^home/', views.home, name="home"),
    url(r'^surukkam/$',views.shrink,name="surukkam"),
    url(r'^(?P<inputURL>[0-9a-zA-Z]+)/$',views.retrieve,name="virivu"),
    url(r'', RedirectView.as_view(pattern_name='home', permanent=False))
]

Solution

  • it is redirecting because you missed ^$ at the end of home URL.

    urlpatterns = [
        url(r'^admin/$', admin.site.urls),
        url(r'^home/$', views.home, name="home"),
        url(r'^surukkam/$',views.shrink,name="surukkam"),
        url(r'^(?P<inputURL>[0-9a-zA-Z]+)/$',views.retrieve,name="virivu"),
        url(r'^$', RedirectView.as_view(pattern_name='home', permanent=False))
    ]
    

    ^$ - it is a regular expression that specifies the start and end points of a URL string.

    whenever your Django detects the empty string it will direct to this URL.