如何在 Django 下将 domain.com 重定向到 WWW.domain.com? [英] How do I redirect domain.com to WWW.domain.com under Django?

查看:28
本文介绍了如何在 Django 下将 domain.com 重定向到 WWW.domain.com?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Django 站点中使用 301 将 domain.com/... 的所有请求重定向到 www.domain.com/...?

How do I go about redirecting all requests for domain.com/... to www.domain.com/... with a 301 in a django site?

显然这不能在 urls.py 中完成,因为你只能在那里得到 URL 的路径部分.

Obviously this can't be done in urls.py because you only get the path part of the URL in there.

我不能在 .htaccess 中使用 mod rewrite,因为 .htaccess 文件在 Django 下没有任何作用(我认为).

I can't use mod rewrite in .htaccess, because .htaccess files do nothing under Django (I think).

我在猜测中间件或 apache conf 中的某些内容?

I'm guessing something in middleware or apache conf?

我在带有 Plesk 的 Linux 服务器上运行 Django,使用 mod WSGI

I'm running Django on a Linux server with Plesk, using mod WSGI

推荐答案

就配置而言,有人指出的 WebFaction 讨论是正确的,您只需要自己应用它,而不是通过控制面板.

The WebFaction discussion someone pointed out is correct as far as the configuration, you just have to apply it yourself rather than through a control panel.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

放入 .htaccess 文件,或在适当的上下文中放入主 Apache 配置中.如果在主要 Apache 配置中的 VirtualHost 内部,则您的 ServerName 为 www.example.com,ServerAlias 为 example.com,以确保虚拟主机处理这两个请求.

Put in .htaccess file, or in main Apache configuration in appropriate context. If inside of a VirtualHost in main Apache configuration, your would have ServerName be www.example.com and ServerAlias be example.com to ensure that virtual host handled both requests.

如果您无权访问任何 Apache 配置,如果需要,可以使用 Django WSGI 应用程序入口点周围的 WSGI 包装器来完成.类似的东西:

If you don't have access to any Apache configuration, if need be, it can be done using a WSGI wrapper around the Django WSGI application entry point. Something like:

import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()

def application(environ, start_response):
  if environ['HTTP_HOST'] != 'www.example.com':
    start_response('301 Redirect', [('Location', 'http://www.example.com/'),])
    return []
  return _application(environ, start_response)

修复此问题以将 URL 包含在站点中并处理 https 留给读者作为练习.:-)

Fixing this up to include the URL within the site and dealing with https is left as an exercise for the reader. :-)

这篇关于如何在 Django 下将 domain.com 重定向到 WWW.domain.com?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆