Htaccess Redirect http>https CI3

47 Views Asked by At

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?

1

There are 1 best solutions below

1
MrWhite On

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 .htaccess file.

You should also be proxying the request to HTTPS, not HTTP. Since this is presumably a common .htaccess file 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 L flag (since it is no longer the last rule).

For example:

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

RewriteCond %{HTTP_HOST} !^www\.example.com
RewriteCond %{HTTP_HOST} ^(.+).example.com
RewriteRule ^([^/]*)$ https://example.com/account/name/%1 [P]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?/$1 [L]

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 L and QSA flags are not required on that rule.)