【问题标题】:How to redirect http url to https for django application served by Apache如何为 Apache 提供的 django 应用程序将 http url 重定向到 https
【发布时间】:2019-01-22 22:38:05
【问题描述】:

我想要实现的是,当我浏览 http://example.com:8080 时,它会被重定向到 https://example.com:8080

我的 Web 应用程序是用 Django 编写的,我的设置中有以下行:

SECURE_SSL_REDIRECT = True

example.com 的 httpd 配置如下所示:

LISTEN 8080
<VirtualHost *:8080>
  ServerName example.com

  SSLEngine on
  SSLCertificateFile /path_to_cer
  SSLCertificateKeyFile /path_to_key
  SSLCertificateChainFile /path_to_iterm.cer

  RewriteEngine On
  RewriteCond %{HTTPS} off
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

  Alias /static /path_to_mysite/static
  <Directory /path_to_mysite/static>
      Require all granted
  </Directory>

  <Directory /path_to_mysite_wsgi_dir>
      <Files wsgi.py>
          Require all granted
      </Files>
  </Directory>

  WSGIDaemonProcess mysite python-path=/path_to_mysite:/path_to_mysite_python_packages display-name=%{GROUP}
  WSGIProcessGroup mysite
  WSGIApplicationGroup %{GLOBAL}
  WSGIScriptAlias / /path_to_mysite_wsgi.py
</VirtualHost>

当我浏览http://example.com时,使用这些配置,我会得到以下错误:

Bad Request
Your browser sent a request that this server could not understand.
Reason: You're speaking plain HTTP to an SSL-enabled server port.
Instead use the HTTPS scheme to access this URL, please.

有什么想法吗?

【问题讨论】:

  • 您不能从一个端口同时提供 HTTP 和 HTTPS。 8080 端口将只能接受 HTTPS 请求。
  • 顺便说一句,不要使用python-path 指向您的虚拟环境站点包。阅读modwsgi.readthedocs.io/en/develop/user-guides/…,了解如何正确配置虚拟环境。
  • 我很高兴在我的帖子下看到您的评论 :) 我记得当我使用 python-home 指向我的虚拟环境时总是遇到问题,设置 python-path 解决了这些问题(不幸的是,我不记得有什么问题)。但现在因为您的评论,我删除了python-path,并改用python-home,看来一切正常!我不知道为什么:D

标签: django apache https httpd.conf


【解决方案1】:

您可以将流量从 8080 重定向到 https:

<VirtualHost *:8080>
  ServerName example.com
  RewriteEngine on
  RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

然后在端口 443 上启用 ssl,这是 https 请求的默认端口:

<VirtualHost *:443>
  ServerName example.com

  SSLEngine on
  SSLCertificateFile /path_to_cer
  SSLCertificateKeyFile /path_to_key
  SSLCertificateChainFile /path_to_iterm.cer

  RewriteEngine On
  RewriteCond %{HTTPS} off
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

  Alias /static /path_to_mysite/static
  <Directory /path_to_mysite/static>
      Require all granted
  </Directory>

  <Directory /path_to_mysite_wsgi_dir>
      <Files wsgi.py>
          Require all granted
      </Files>
  </Directory>

  WSGIDaemonProcess mysite python-path=/path_to_mysite:/path_to_mysite_python_packages display-name=%{GROUP}
  WSGIProcessGroup mysite
  WSGIApplicationGroup %{GLOBAL}
  WSGIScriptAlias / /path_to_mysite_wsgi.py
</VirtualHost>

【讨论】:

  • 我的第一个意图是在端口 8080 上同时使用 http 和 https。但正如 Graham 指出的那样,这是不可能的。所以我不能将此标记为正确答案。但是您的回答对解决我的问题有很大帮助。谢谢。
  • Np,我想我会稍微扩展他的评论,很高兴它有所帮助。
猜你喜欢
  • 2020-08-07
  • 2019-11-08
  • 1970-01-01
  • 2019-12-17
  • 2015-11-02
  • 2011-06-11
  • 1970-01-01
  • 2013-09-27
相关资源
最近更新 更多