php - 使用 .htaccess 为子域强制使用 SSL HTTPS

标签 php apache .htaccess mod-rewrite ssl

我通常在网站上使用此代码强制使用 SSL:

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

我从 here 得到的

我希望它仅适用于特定的子域

例如,如果您要访问 http://sub.domain.org,它应该重定向到 https://sub.domain.org

我有一种预感,我需要添加另一个 RewriteCond,它基本上表示 被命中的域是 http://sub.domain.org ,但我不知道如何编写这段代码。

我一直在查看其他 stackoverflow 问题,例如:

Force HTTPS and WWW for domain and only HTTPS for subdomains HTACESS

Force SSL/https using .htaccess and mod_rewrite

和 Apache 文档:https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond

我有过这些尝试:

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^(reports\.)?uksacb\.org$ [NC]
RewriteRule ^.*$ https://%1%{REQUEST_URI} [R,L]

有点颠倒了这个 question/answer 中的答案:

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} =reports.uksacb.org
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

但是我仍然无法理解如何正确地做到这一点。

如果有人能向我解释我做错了什么,我需要做些什么才能让它正确,以及如何调试他们的重写条件和规则以确保它正常工作,我将非常感激。有时我认为我的浏览器正在缓存我编写的规则,而我的不同尝试没有任何影响!

我的整个 .htaccess 看起来像这样:

选项 - 多 View

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Force SSL
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

最佳答案

为了避免使用域名或子域名,我使用了以下代码:

  # Redirect HTTP to HTTPS
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

我更喜欢没有 WWW。

%{HTTPS} 如果请求是通过 SSL 提供的,则设置为打开。

%{HTTP_HOST} 协议(protocol)(http://或 https://)和请求(/example-file.txt)之间的所有内容。

%{REQUEST_URI} 服务器地址之后的所有内容——例如,对 http://example.com/my/example-file.txt 的请求将此值设置为 my/example-file.txt。

%{HTTP:X-Forwarded-Proto} 请求 URL 时使用的协议(protocol) — 设置为 http 或 https。

希望对大家有用。

关于php - 使用 .htaccess 为子域强制使用 SSL HTTPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37481681/

相关文章:

php - 检查 PHP 5.6 中类数组常量中元素的存在

Django + Apache + mod_wsgi 权限被拒绝

.htaccess - 使用 .htaccess 修复拼写错误?

php - 重写规则重定向文件夹

jQuery.ajax() 的 Javascript 替代方案 - 面临错误

php - 为 CRUD 操作创建历史表的最佳方式

apache - 无法远程连接到 Node.js 服务器

php - 包含带有 .htaccess 的子文件夹

php - MySQL:通过 PHP 根据逗号分隔值在数据库中插入多行

apache - 如何在 Windows 8.1 上安装 Mahout?