django - 如何为 Apache 提供的 django 应用程序将 http url 重定向到 https
问题描述
我想要实现的是当我浏览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.
有什么想法吗?
解决方案
您可以将流量从 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>
推荐阅读
- sql-server - 使用 DataGrip - Active Directory 连接到 Azure 数据库
- ubuntu - 更改 ubuntu 服务器中特定组的文件模式
- r - 如何选择变量以在带有 R 的公式中使用它们
- spotfire - Spotfire 滚动 YTD 期间计算
- python-3.x - 为什么这显示“有时字符串索引超出范围”?
- haskell - 如何使用 Data.Data?
- javascript - 如何在尝试使用 Razor Pages 删除 ASP.NET Core 中的记录时显示确认消息
- pyspark - 删除前导零pyspark?
- swift - swift:如何在代码中使用带乘数的约束
- python - 如果字符串中存在模式,则匹配模式