I currently have such an .htaccess file that redirects wildcard subdomains, for example, name.example.com, to example.com/account/company/name.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
RewriteCond %{HTTP_HOST} !^www\.example.com
RewriteCond %{HTTP_HOST} ^(.+).example.com
RewriteRule ^([^/]*)$ http://example.com/account/name/%1 [P,L,QSA]
However, when I try to add a redirect from HTTP to HTTPS, the previous redirection stops working...
RewriteCond %{HTTP_HOST} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI}
and instead of having https://name.example.com, I get https://example.com/account/company/name. How can I set up the HTTP to HTTPS redirection to work alongside the previous rules?
The problem is that you've put the rules in the wrong order. The "previous redirection" has not "stopped working", it's just that it is occurring before the canonical redirect from HTTP to HTTPS.
Any canonical redirects (ie. HTTP to HTTPS) need to be first in the
.htaccessfile.You should also be proxying the request to HTTPS, not HTTP. Since this is presumably a common
.htaccessfile for all subdomains and domain apex, it will be processed again after the request has been proxied.I assume you also have a wildcard SSL cert that covers all the wildcard subdomains, otherwise you will naturally get SSL cert browser errors.
Your canonical redirects need to be first. However, your existing rules are also in the wrong order - unless all requests to the subdomains happen to map to physical files and directories?
The HTTP to HTTPS redirect should also be a 301 (although you should first test with a 302) and you must also include the
Lflag (since it is no longer the last rule).For example:
However, that second rule does look a bit strange. You are "proxying" all requests for single path segment URLs to the name of the subdomain. Does it need to be a reverse proxy? Isn't the main domain and all "wildcard" subdomains pointing to the same place on the filesystem? (Aside: The
LandQSAflags are not required on that rule.)