skip to Main Content

I’d like to redirect all visitors to my WordPress website except the translations available for pages in the /cy/ subdirectory:

  • /cy/

so for example

  • https://myoldomain.co.uk/cy/partners/

is not redirected but

  • https://myoldomain.co.uk/partners/
  • https://myoldomain.co.uk/

are redirected.

I have tried lots and this one works in an online tester but not in practice – all domains including those with /cy/ are redirected.

RewriteBase /
RewriteCond %{HTTP_HOST} myoldomain.co.uk
RewriteCond %{REQUEST_URI} !^/(cy|cy/.*)$ 
RewriteRule ^(.*)$ https://mynewdomain.co.uk/$1 [R=301,L]

Any ideas what I am missing?

2

Answers


  1. Chosen as BEST ANSWER

    This may not be pretty but appears to Exclude wp-login.php and the wp admin area from the redirect.

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{HTTP_HOST} (^|.)myoldomain.co.uk [NC]
    RewriteCond %{REQUEST_URI} !^/(cy|cy/.*)$ 
    RewriteCond %{REQUEST_URI} !^/(wp-admin|wp-admin/.*)$ 
    RewriteCond %{REQUEST_URI} !^/(wp-includes|wp-includes/.*)$ 
    RewriteCond %{REQUEST_URI} !^/(wp-content|wp-content/.*)$ 
    RewriteCond %{REQUEST_URI} !^/wp-login.php
    RewriteRule ^(.*)$ https://mynewdomain.co.uk/$1 [R=301,L]
    

  2. RewriteCond %{HTTP_HOST} myoldomain.co.uk
    RewriteCond %{REQUEST_URI} !^/(cy|cy/.*)$ 
    RewriteRule ^(.*)$ https://mynewdomain.co.uk/$1 [R=301,L]
    

    If you are using WordPress then you have a front-controller pattern later in the file that rewrites all non-files to index.php (the WP front-controller). During the second pass of the rewrite engine /index.php is obvsiously not /cy... so the redirect occurs. But this should be visible in the redirect.

    You need to make sure the above redirect only applies to the initial request from the client and not the rewritten request. You can do this by checking against the REDIRECT_STATUS environment variable (which is empty on the initial request).

    For example:

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{HTTP_HOST} (^|.)myoldomain.co.uk [NC]
    RewriteCond %{REQUEST_URI} !^/(cy|cy/.*)$ 
    RewriteRule ^(.*)$ https://mynewdomain.co.uk/$1 [R=301,L]
    

    And this needs to go near the top of the file, before the WP front-controller pattern.

    You will need to clear your browser cache before testing. Preferably test with 302 (temporary) redirects to avoid potential caching issues.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search