regexapachemod-rewrite

mod rewrite split and replace


I need an internal redirect, where category-slug is a dynamic value, that schould be appended after the ~

/category/**category-slug**  /blog/?ucterms=category~**category-slug**

Is that possible with mod rewrite? I have seen solutions like ?name=$1 name/$1. But how can isolate the value right from the last slash and put it after the tilde? Otherwise I would have to write a single line for every category.


Solution

  • If you are only matching the first level after category:

    RedirectMatch 301 /category/([^/]+) /blog/?ucterms=category~$1
    

    If you want to grab everything after /category/ till the end of the URL (this will include multiple levels and forward slashes etc):

    RedirectMatch 301 /category/(.+) /blog/?ucterms=category~$1
    

    I have used + for as the Quantifier so that it will redirect if there is something after ie /category/ by itself will not redirect.

    Also please use the code you want such as 301, 302 etc as an example.

    Using RedirectMatch will immediately redirect and stop any further processing of the .htaccess if you are using that. So you can add it where appropriate in the file.

    Adding example with RewriteRule, you can modify each side as needed. Also as this is a simple redirect you can exclude using RewriteCond.

    RewriteEngine On
    RewriteRule ^category/([^/]+)/?$ /blog/?ucterms=category~$1 [R=301,L]
    

    Note the L here would mean do not process any other rules after this rule. So it is similar to the first option provided.

    Think of it this way if you had 10 rules for various operations, do you want to keep processing those rules before redirecting if there is a match or just redirect early and skip all that stuff. Either way one or the other is going to run for every request to the server.