S
S
Sergey Nizhny Novgorod2016-07-26 06:17:05
Django
Sergey Nizhny Novgorod, 2016-07-26 06:17:05

Is htaccess django necessary?

Now faced with the fact that I usually write redirects in the htaccess file for php projects. So two questions:
1) is this file needed for django? Yes, how do you work with it?
2) If not, how to prescribe redirects?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2016-07-26
@Terras

as Viktor Melnikov wrote , don't do it ever
Nobody uses Apache -- nginx + uwsgi (gunicorn)
Redirection happens in nginx

V
Viktor Melnikov, 2016-07-26
@Viteran33

Regarding redirects, django has the redirects app for this https://docs.djangoproject.com/en/1.9/ref/contrib/... , but it's worth clarifying that a redirect only works if the initial link returns a 404. Further, for a redirect to WWW in settings.py PREPEND_WWW = True For the opposite case, middleware is written, for example, like this.

class UrlMiddleware(object):

  def process_request(self, request):
      host = request.get_host()
      old_url = [host, request.path]
      new_url = old_url[:]
      
      if (settings.REMOVE_WWW and old_url[0] and old_url[0].startswith('www.')):
          new_url[0] = old_url[0][4:]
      
      if new_url != old_url:
          try:
              urlresolvers.resolve(new_url[1])
          except urlresolvers.Resolver404:
              pass
          else:
              if new_url[0]:
                  newurl = "%s://%s%s" % (
                      request.is_secure() and 'https' or 'http',
                      new_url[0], urlquote(new_url[1]))
              else:
                  newurl = urlquote(new_url[1])
              if request.GET:
                  newurl += '?' + request.GET.urlencode()
              return http.HttpResponsePermanentRedirect(newurl)
      return None

and in settings write REMOVE_WWW = True, for a redirect to a slash APPEND_SLASH = True , again it will work for a slash only if it returns 404 without a slash.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question