Ask Your Question
4

How do I add a 301 redirect containing the query parameter "?page=" in my Django "urls.py" file?

asked 2021-11-05 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-05-22 09:00:00 +0000

lalupa gravatar image

You can add a 301 redirect in your Django "urls.py" file by defining a new URL pattern and using the "RedirectView" class to redirect the old URL with the query parameter to the new URL. Here's an example:

from django.urls import path, re_path
from django.views.generic import RedirectView

urlpatterns = [
    # Your other URL patterns...

    # Redirect URLs with ?page=x to the same URL without the query parameter
    re_path(r'^old-url/$', RedirectView.as_view(url='/new-url/')),
    re_path(r'^old-url/(?P<page>\d+)/$', RedirectView.as_view(url='/new-url/')),
]

In this example, the first "repath" pattern matches the URL "old-url/" without any query parameters, and simply redirects it to "new-url/". The second "repath" pattern matches URLs with the query parameter "?page=x", where "x" is any numeric value, and captures the value of "x" as a named parameter "page". It then redirects the URL to "new-url/" without the query parameter.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-05 11:00:00 +0000

Seen: 11 times

Last updated: May 22 '22