子域的动态 htaccess 处理、丢失的流量和 HTTPS

Dynamic htaccess handling of subdomain, missing traffic & HTTPS

我对 .htaccess 和 RegEx 还是很陌生,对此感到非常沮丧,但我可能过于复杂了。基本上:

我的尝试:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www. [NC] 
RewriteRule ^(.*)$  [L] 
RewriteCond %{HTTP_HOST} domain1\.ca [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L]
RewriteCond %{HTTP_HOST} !domain1\.ca [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L]
RewriteCond %{REQUEST_URI} ^/foo.* [NC]
RewriteRule ^ %{REQUEST_SCHEME}://foo\.%{HTTP_HOST}%{REQUEST_URI} [L]
RewriteRule "^/foo/(.+)" "%{REQUEST_SCHEME}://foo.%{HTTP_HOST}/" [L,NS,QSA,R=301]

一些例子:

incoming url:                               should become:
http://www.domain1.com/foo/blah          => https://foo.domain1.com/blah
https://example.com/foo/blah.html        => http://foo.example.com/blah.html
http://www.domain1.com/foo/index.php/foo => https://foo.domain1.com/foo
https://example.com/blah/blah.html       => http://example.com/blah/blah.html 

我希望这是有道理的(我不知所措而且迟到了!)- 谢谢!

这些规则是根据你的问题顺序翻译的

RewriteEngine On

# Remove www from domain, keep scheme (http or https)
RewriteCond %{HTTP_HOST}#%{HTTPS}s ^www\.([^#]+)#(?:off|on(s)) [NC]
RewriteRule ^ http%2://%1%{REQUEST_URI} [R=302,L]

# force https for {domain1,domain2}
RewriteCond %{HTTP_HOST} ^(?:domain1|domain2)\. [NC]
RewriteCond %{HTTPS} off [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]

# force http for others
RewriteCond %{HTTP_HOST} !^(?:domain1|domain2)\. [NC]
RewriteCond %{HTTPS} on [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]

# foo subfolder -> foo subdomain
RewriteCond %{HTTP_HOST} !^foo\. [NC]
RewriteCond %{REQUEST_URI}#%{HTTPS}s ^/foo/([^#]+)#(?:off|on(s)) [NC]
RewriteRule ^ http%2://foo.%{HTTP_HOST}/%1 [R=302,L]

# hide index.php for foo subdomain
RewriteCond %{HTTP_HOST} ^foo\. [NC]
RewriteRule ^index\.php(?:$|/(.*)) / [R=302,L]

# (internal rewrite) foo subdomain -> foo's root index
RewriteCond %{HTTP_HOST} ^foo\. [NC]
RewriteCond %{REQUEST_URI} !^/foo/ [NC]
RewriteRule ^ /foo/index.php [L]

# default rule (root index)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /index.php [L]

这很丑,我同意。但这应该会如您所愿。它已经在本地服务器上进行了测试,您展示的所有示例测试都刚刚通过。

注意:我特意使用了 302 重定向。当您这边一切都好时,只需切换回 301