.htaccess重定向https,如果不存在子域,则自动添加www



需要帮助,

对于我在Planethoster托管的网站,我试图将HTTP强制为HTTPS,而不使用www自动使用https://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] 

但当我只使用网址mydomain.com而不使用www它返回一个奇怪的url:https://www.mydomain.com/https://mydomain。com/(com之前没有espace(

因此,我无法使用mydomain.com访问我的网站,我必须手动将www

有人能帮我吗?

如果没有其他子域,则强制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

这些应该涵盖所有场景,

  • http://example.com/abc
  • http://www.example.com/abc
  • http://abc.example.com/abc
  • https://abc.example.com/abc
  • https://www.example.com/abc
  • https://example.com/abc

最新更新