【问题标题】:.htaccess redirect https and automatically add www. if no subdomain exists.htaccess 重定向 https 并自动添加 www。如果不存在子域
【发布时间】:2021-09-26 01:16:55
【问题描述】:

需要帮助,

对于我在 Planethoster 托管的网站,我尝试使用 https 自动强制 HTTPHTTPS 并且没有 www.: //www.

在 .htaccess 中使用此代码

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301] 

但是当我只使用没有 www. 的 url mydomain.com 时,它会返回一个奇怪的 url: https://www.mydomain。 com/https:/我的域名。 com/(com 前没有空格)

为了让我无法通过 mydomain.com 访问我的网站,我必须手动输入 www.

有人可以帮我吗?

【问题讨论】:

  • 尝试清除浏览器缓存并将这些规则放在 htaccess 顶部 RewriteEngine on 下方

标签: .htaccess web


【解决方案1】:

如果没有其他子域,则强制 SSL 并要求 www。 你可以试试这个,

# if ssl is off and starts with www or no subdomain,
# redirect to https://www.
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.example.com [OR]
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

# if ssl and no subdomain, redirect to www.
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

# if ssl off, and there's a subdomain that's not www,
# just use the current subdomain but redirect to https
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.example.com
RewriteCond %{HTTP_HOST} ^(.*)\.example.com
RewriteRule ^ https://%1.example.com%{REQUEST_URI} [L,R=301]

你可以在这里测试它们,https://htaccess.madewithlove.be

这些应该涵盖所有场景,

【讨论】:

  • @AmitVerma 想评论为什么?
  • 如果没有 SSL 并且主机是 www.example.com 或 example.com,则匹配。如果匹配,它将重定向到 www... 在后续请求中,如果域是 example.com,则唯一的 https on 是匹配的,但它不会匹配。它将有www
  • 对不起,我还以为你在第一个条件下使用 [OR]。你的规则很好。 +1。
  • @AmitVerma 一切都好。 Legit 认为有问题。
猜你喜欢
  • 2012-08-28
  • 2018-06-02
  • 2016-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-19
  • 2016-01-21
相关资源
最近更新 更多