Search code examples
phpwordpress.htaccessmod-rewrite

Redirect all TLD's to .com with subfolder in Wordpress


While building my first Wordpress website I have a few issues with the URL. Since my website is multi language I have installed the Polylang plugin (Free version).

This together with permalinks seems to work. What I have is for every language a different subfolder after the domain name:

www.example.com/nl/

www.example.com/fr/contact/

www.example.com/be/page-about-info/

What I also try to achieve is that the domainnames with different TLD's forward to the .com domain with the folder language.

I have www.example.com but also www.example.nl, www.example.fr, www.example.be and www.example.de.

example.nl and example.be should both go to .com/nl/

I need to add rules to my .htaccess file but i cannot get it working. Probably because the Polylang and Wordpress also have their rules.

What i have is:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteCond %{HTTP_HOST} example\.(fr|nl|de) [NC]
RewriteRule ^(.*) https://www.example.com/%1/$1/ [R,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Where this part is the part I added myself for the redirect:

RewriteCond %{HTTP_HOST} example\.(fr|nl|de) [NC]
RewriteRule ^(.*) https://www.example.com/%1/$1/ [R,L]

I am not sure if my testing messed up my browser and the URL is being cashed but for some reason I cannot get the redirect work.

Anyone who can help me with this?

Edit: After testing a bit I see that for example: https://www.example.fr/test/ works and redirects to https://www.example.com/fr/test/


Solution

  • You likely want:

    # for as-is replacements, you can pack them in a single statement
    RewriteCond %{HTTP_HOST} example\.(fr|nl|de) [NC]
    RewriteRule ^(.*) https://www.example.com/%1/$1 [R=301,QSA,L]
    
    # for altered replacements each destination will need its own statement
    RewriteCond %{HTTP_HOST} example\.(be|xy|etc) [NC]
    RewriteRule ^(.*) https://www.example.com/nl/$1 [R=301,QSA,L]
    
    • R=301 issues a permanent redirect, simply R will issue a 302.
    • QSA will Append the Query String, if necessary.