Reputation: 27195
I want to redirect
http://www2.mydomain.com/some-filename.php
to http://newmydomain.com/some-filename.php
And
https://www2.mydomain.com/some-filename.php
to https://newmydomain.com/some-filename.php
My "www2.mydomain.com" domain doesn't have the valid SSL, but still if the user access https then I need to redirect him to new domain with https only.
I have written the following code in .htaccess
but it is redirecting to HTTP
all the time.
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS_HOST} ^www2\.mydomain\.com$ [NC]
RewriteRule ^(.*)$ https://newmydomain.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^www2\.mydomain\.com$
RewriteRule ^(.*)$ http://newmydomain.com/$1 [L,R=301]
</ifModule>
Please let me know what I am doing wrong and what is the correct code to do this kind of redirects.
Upvotes: 0
Views: 1786
Reputation: 143966
You aren't checking whether the incoming request is HTTPS or not. You can combine the two with a bit of clever regex grouping:
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www2\.mydomain\.com$ [NC]
RewriteCond %{HTTPS}:s (on:(s)|off:s)
RewriteRule ^(.*)$ http%2://newmydomain.com/$1 [L,R=301]
</ifModule>
There isn't an %{HTTPS_HOST}
variable, as it's the "Host:" request field. All the %{HTTP_(something)}
variables are request fields, e.g. %{HTTP_USER_AGENT}
, %{HTTP_COOKIE}
, %{HTTP_REFERER}
, are all request fields; User-Agent:
, Cookie:
, Referer:
.
The second condition checks if the request is HTTPS or not, and if so (on
), it captures the "s" which is backreferenced by %2
, thus turning the redirect to https://
, otherwise, just http://
.
Upvotes: 1