【问题标题】:Force SSL HTTPS for subdomain with .htaccess使用 .htaccess 对子域强制使用 SSL HTTPS
【发布时间】:2016-09-25 16:29:41
【问题描述】:

我有这个代码通常用于在网站上强制使用 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 看起来像这样:

选项 - 多视图

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]

【问题讨论】:

  • RewriteCond %{HTTP_HOST} =reports.uksacb.org 应该可以工作。清除浏览器缓存并在第二条规则中使用该条件重新测试
  • @anubhava Right 会试一试,看看进展如何,谢谢!
  • 如果您有一个有效的子域证书,该证书将通过扩展对主域有效,那么只需将所有域/子域设置为 TLS 保护。

标签: php apache .htaccess mod-rewrite ssl


【解决方案1】:

为了调试,我使用了一个我找到的网站https://htaccess.madewithlove.be/

使用您提供的规则

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

我遇到了一个错误

RewriteCond %{HTTPS} !=on

这可能对你有用

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/%$1 [R,L] 

https://www.sslshopper.com/apache-redirect-http-to-https.html找到上面的例子

【讨论】:

  • 第一个网页不再活跃
  • 谢谢。还不知道那个
【解决方案2】:

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

  # 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 提供请求,则设置为 on。

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

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

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

我希望它对任何人都有用。

【讨论】:

  • 我花了太长时间试图找到解决方案。非常感谢!
猜你喜欢
  • 2014-01-20
  • 1970-01-01
  • 2017-08-22
  • 2011-05-22
  • 2015-07-05
  • 1970-01-01
  • 2016-06-11
  • 2017-06-18
相关资源
最近更新 更多