Search code examples
apache.htaccesshttp-redirectmod-rewriteurl-rewriting

htaccess redirect 301 without a folder


i'm trying to do

  • redirect a site from a.example to b.example
  • folder a.example/c/ must not redirect
  • a.example/test.php must be redirected to a.example/c/test.php

i try this .htaccess :

RewriteEngine on

RewriteRule !^c($|/) https://b.example/ [L,R=301]

Redirect 301 /test.php https://www.a.example/c/test.php

but this second 301 redirect doesn't redirect?


Solution

  • The first mod_rewrite RewriteRule directive redirects everything that does not start blog to b.example. This will naturally redirect /test.php as well. Changing the order of these rules will make no difference since Redirect is a mod_alias directive and is processed later1 regardless of the order of the directives. (1earlier on "LiteSpeed", opposite to Apache.)

    You would need to do something like this instead, using mod_rewrite throughout and reversing the order of the two rules:

    RewriteEngine On
    
    RewriteRule ^test\.php$ /c/$0 [R=301,L]
    RewriteRule !^c($|/) https://b.example/ [L,R=301]
    

    This does assume that the second domain (b.example) points to a different server.

    The $0 backreference in the substitution string in the first rule contains the full URL-path that is matched by the RewriteRule pattern, ie. test.php in this example (saves repetition).

    Test with a 302 (temporary) redirect first to avoid potential caching issues. You will need to clear your browser cache before testing.