Ok, I found a solution.
By default in WP there is an option to filter categories by tags. E.g. https://example.com/category_name?tag=tag_name
. I added a rewrite rule and redirection:
https://developer.wordpress.org/reference/functions/add_rewrite_rule/
add_action( 'init', function () {
add_rewrite_rule( '([a-z0-9-]+)\/tag\/([a-z0-9-]+)\/?$', 'index.php?category_name=$matches[1]&tag=$matches[2]', 'top' );
} );
https://developer.wordpress.org/reference/hooks/template_redirect/
add_action( 'template_redirect', function () {
if ( is_category() && is_tag() && ! empty( $_GET['tag'] ) ) {
wp_redirect( get_category_link( get_the_category()[0] ) . 'tag/' . get_query_var( 'tag' ) . "https://wordpress.stackexchange.com/" );
exit();
}
} );
Of course it’s just such a basic code. It will require additional adjustments, e.g. for SEO.