Home  >  Q&A  >  body text

Unable to implement this htaccess redirect

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

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

My goal 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 the help.

P粉806834059P粉806834059171 days ago1369

reply all(1)I'll reply

  • P粉593649715

    P粉5936497152024-04-05 13:03:26

    If the subdomain and main domain point to the same location (or a subdirectory of the latter), an infinite loop will occur.

    In this case you will need to use mod_rewrite (instead of mod_alias) and explicitly check the requested hostname.

    But you also used a 301 Permanent redirect. You need to use 302 instead. 301s are persisted by browser caches, so you need to make sure you clear all caches 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/rrreee [R,L]

    Note that RewriteRule pattern (first argument) matches URL paths that do not start with a slash (unlike the mod_alias Redirect directive).

    $0 A backreference contains a URL path that matches the entire RewriteRule pattern. ie. In this case mypage.php. This just saves duplication since you are redirecting to the same URL path at the target.

    This defaults to a 302 temporary redirect.

    reply
    0
  • Cancelreply