Search code examples
regex.htaccessreplacequery-stringdokuwiki

Query String: Replace the Same Text Multiple Times


Background: I recently changed in a DokuWiki installation every string which contains a specific product name to another. Now I have to redirect hard-coded links to the new URL.

The URLs look like:

past:    example.com/wiki/doku.php?id=sales:producta:descr:producta
present: example.com/wiki/doku.php?id=sales:productb:descr:productb

Issue: I should replace the string producta to productb. This string can occur several times in a URL. Therefore it should be replaced regardless the number of occurences.

I found several ways to replace a unique string. But I need to replace every single occurrance of this string in the URL. A working replacement before the question mark ist possible, but i didn't found a solution to manipulating the querystring like this.

Is there a way to achieve this replacement?


Solution

  • It's quite tricky, but it can be done. Try adding this to the .htaccess file in your web document root folder (often public_html or htdocs):

    Options -Multiviews
    RewriteEngine On
    # If the query string contains producta, capture it to %1
    RewriteCond %{QUERY_STRING} ^(.+?producta.*)
    # ... and bring it down to the url, temporarily inserting @@
    RewriteRule ^(.+) $1@@%1? [DPI]
    # Rewrite product a to product b but only if @@ is in the string
    RewriteRule ^([^@]+@@.*)producta(.*) $1productb$2 [N] 
    # Remove @@
    RewriteRule ^([^@]+)@@(.*) $1?$2 [L]
    

    This assumes that mod_rewrite is both installed and activated for .htaccess files. If you are not sure, to check if mod_rewrite is even installed, look at the list of installed modules in the output of phpinfo(); By default, mod_rewrite is not enabled for .htaccess files. If you are managing your own server, open httpd.conf and make sure that the webroot directory block contains one of these lines: AllowOverride FileInfo or AllowOverride All