i'm stuck using htaccess redirection, mixing some answers [1] [2] about htaccess redirection.
My goal is to redirect every subdomain (not www) to my main one ( starting with https://www. ), keeping the Request_URI (like specified folder) as it is.
Here is what i've done:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.mydomain\.fr$ [NC]
# OR : RewriteCond .* ^(.+)\.%{HTTP_HOST}%{REQUEST_URI}$ [NC]
RewriteCond %{HTTP_HOST} !^www\.mydomain\.fr$ [NC]
RewriteRule ^ https://www.mydomain.fr%{REQUEST_URI} [L,R=301,QSA]
This config do redirect (strong text are bad redirection) :
- test.mydomain.fr => https://www.mydomain.fr
- test.mydomain.fr/foo => https://www.mydomain.fr/foo
- mydomain.fr => https://www.mydomain.fr
- https://foo.mydomain.fr => https://foo.mydomain.fr
- www.mydomain.fr => http://www.mydomain.fr
Swapping
RewriteCond %{HTTP_HOST} !^www\.mydomain\.fr$ [NC]
to
RewriteCond %{HTTP_HOST} !^https://www\.mydomain\.fr [NC]
gave me an error of bad redirection.
My thoughts was to check if the HTTP_HOST is in format https://www.mydomain, if not redirect to the good URL with REQUEST info
RewriteRule ^ https://www.mydomain.fr/%{REQUEST_URI}
Why is there a bad redirection ? Do I have to write 2 set of Condition and Rule to check first the subdomain, then the HTTPS ? (I'm currently trying to make the redirection using one rule and several conditions, this may not be the best practice)
EDIT : My goal is to have these redirection:
- test.mydomain.fr => https://www.mydomain.fr
- test.mydomain.fr/foo => https://www.mydomain.fr/foo
- mydomain.fr => https://www.mydomain.fr
- https://foo.mydomain.fr => https://www.mydomain.fr
- www.mydomain.fr => https://www.mydomain.fr
Thanks in advance for any answers/ideas.
EDIT 2:
I've tried the Larzan answer on THIS question, and it seems to do what i want except one thing : If my URL in my browser is something like https://foobar.mydomain.fr
, the browser shows me a big red warning about security, and i have to accept the risk, then the redirection is done to https://www.mydomain.fr
. How can i removed this warning ?
#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.mydomain
RewriteRule ^(.*)$ https://www.mydomain.fr%{REQUEST_URI} [L,R=301]
#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]