Rewriting a specific URL: adding a subdirectory

I am working on a WordPress-site and I have an URL like

https://example.com/technische-uebersetzungen

What I need is:

https://example.com/subdirectory/technische-uebersetzungen

My code has a bug, it does not rewrite the URL. I placed it at the end of the existing .htaccess file.

RewriteEngine On
RewriteRule ^technische-uebersetzungen/(.*)$ /blog/technische-uebersetzungen/$1 [R=301,NC,L]

Does anybody know, what is that bug?

1 answer

  • answered 2022-01-18 01:28 MrWhite

    My code has a bug, it does not rewrite the URL. I placed it at the end of the existing .htaccess file.

    One "bug" is placing that rule at the end of the .htaccess file. By placing the rule after the WordPress code block, the request is first rewritten to index.php and your rule is never processed.

    This "redirect" needs to go at the top of the .htaccess file, before the WordPress code block (ie. before the # BEGIN WordPress comment marker).

    RewriteRule ^technische-uebersetzungen/(.*)$ /blog/technische-uebersetzungen/$1 [R=301,NC,L]
    

    This rule matches /technische-uebersetzungen/<anything> (note the mandatory trailing slash after the first path segment) and the <anything> part is copied onto the end of the target URL. This is not mentioned in your example.

    Your example URL is for /technische-uebersetzungen exactly (no trailing slash). And nothing is appended to the end of the target URL.

    Try the following instead at the top of the .htaccess file:

    RewriteRule ^technische-uebersetzungen(/.*)?$ /blog/$0 [R=301,NC,L]
    

    This will match /technische-uebersetzungen or /technische-uebersetzungen/<anything> and redirect to the same URL with a /blog/ prefix.

    NB: You must test this first with a 302 (temporary) redirect to avoid any potential caching issues and only change this to a 301 (permanent) redirect - if that is the intention - once you have confirmed this works as intended.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum