如何在 Django 下将domain.com重定向到WWW.domain.com?

发布于 2024-08-22 08:09:50 字数 308 浏览 8 评论 0原文

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

显然这不能在 urls.py 中完成,因为你只能在其中获取 URL 的路径部分。

我无法在 .htaccess 中使用 mod rewrite,因为 .htaccess 文件在 Django 下不执行任何操作(我认为)。

我猜中间件或 apache conf 中有什么东西?

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

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

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

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

I'm guessing something in middleware or apache conf?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

以为你会在 2024-08-29 08:09:50

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

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,以确保虚拟主机处理这两个请求。

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

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 留给读者作为练习。 :-)

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]

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.

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)

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

吃兔兔 2024-08-29 08:09:50

PREPEND_WWW 设置就是这样做的。

The PREPEND_WWW setting does just that.

浮云落日 2024-08-29 08:09:50

有一种一种轻量级的方法来做到这一点涉及虚拟主机 和 mod_alias 重定向指令。您可以定义两个 VirtualHost,一个保存重定向,另一个保存 站点配置

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
    # real site configuration
</VirtualHost>

这样就可以完成任务了。

There is a lightweight way to do that involving VirtualHosts and mod_alias Redirect directive. You can define two VirtualHosts, one holding the redirect and another holding the site configuration:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
    # real site configuration
</VirtualHost>

And that will do the job.

留蓝 2024-08-29 08:09:50

这也可以通过中间件来完成。

一些示例:

这是 snippet-510 的更好版本:

class UrlRedirectMiddleware(object):
    """
    This middleware lets you match a specific url and redirect the request to a
    new url. You keep a tuple of (regex pattern, redirect) tuples on your site
    settings, example:

    URL_REDIRECTS = (
        (r'(https?)://(www\.)?sample\.com/(.*)
, r'\1://example.com/\3'),
    )
    """
    def process_request(self, request):
        full_url = request.build_absolute_uri()
        for url_pattern, redirect in settings.URL_REDIRECTS:
            match = re.match(url_pattern, full_url)
            if match:
                return HttpResponsePermanentRedirect(match.expand(redirect))

This also can be done with a middleware.

Some examples:

This is a better version of snippet-510:

class UrlRedirectMiddleware(object):
    """
    This middleware lets you match a specific url and redirect the request to a
    new url. You keep a tuple of (regex pattern, redirect) tuples on your site
    settings, example:

    URL_REDIRECTS = (
        (r'(https?)://(www\.)?sample\.com/(.*)
, r'\1://example.com/\3'),
    )
    """
    def process_request(self, request):
        full_url = request.build_absolute_uri()
        for url_pattern, redirect in settings.URL_REDIRECTS:
            match = re.match(url_pattern, full_url)
            if match:
                return HttpResponsePermanentRedirect(match.expand(redirect))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文