can't achieve this htaccess redirection

Viewed 22

I have a maindomain.com that contains a website, and some pages here should be redirected temporarily to my subdomain tmp.maindomain.com. So I used this redirection, it redirect to the tmp.maindomain.com and I get an infinite loop redirection to tmp.maindomain.com:

redirect 301 /mypage.php https://tmp.maindomain.com/mypage.php

My target is that, if any user tries to access https://www.maindomain.com/mypage.php or https://maindomain.com/mypage.php he should be redirected 302 to https://tmp.maindomain.com/mypage.php.

Thank you for your help guys.

1 Answers

You will get an infinite loop if the subdomain and main domain point to the same place (or a subdirectory of the later).

In which case you will need to use mod_rewrite (as opposed to mod_alias) and explicitly check the requested hostname.

some pages here should be redirected temporarily

But you are also using a 301 permanent redirect. You need to use a 302 instead. 301s are cached persistently by the browser, so you need to make sure all caches are cleared before testing.

Try the following at the top of the subdomain's .htaccess file, before any existing mod_rewrite directives.

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?maindomain\.com [NC]
RewriteRule ^mypage\.php$ https://tmp.maindomain.com/$0 [R,L]

Note that the URL-path matched by the RewriteRule pattern (1st argument) does not start with a slash (unlike the mod_alias Redirect directive).

The $0 backreference contains the URL-path that is matched by the entire RewriteRule pattern. ie. mypage.php in this example. This simply saves repetition, since you are redirecting to the same URL-path at the target.

This defaults to a 302 temporary redirect.

Related