How to have multiple rewrite endpoints in the same URL?

I also need this to work:

example.com/nice-page/my-gallery/animals/cats/my-lightbox/1234

Where I’d like to register my-lightbox as an additional endpoint or
query_var, because it could be used independently from without
my-gallery, such as:

example.com/another-page/my-lightbox/2345

Here’s an example of doing it using add_rewrite_rule():

add_action( 'init', function() {
    // This will let you use get_query_var( 'my-gallery' ).
    add_rewrite_endpoint( 'my-gallery', EP_PAGES );

    // This will let you use get_query_var( 'my-lightbox' ).
    add_rewrite_endpoint( 'my-lightbox', EP_PAGES );

    add_rewrite_rule(
        '(.?.+?)/(?:my-gallery/(.+?)/my-lightbox/(\d+)|my-gallery/(.+?)|/?my-lightbox/(\d+))/?$',
        'index.php?pagename=$matches[1]&my-gallery=$matches[2]&my-lightbox=$matches[3]',
        'top'
    );

    // This is just for testing purposes. You should instead go to the Permalink
    // Settings page and click on the Save Changes button to flush the rules. =)
    //flush_rewrite_rules();
} );

[EDIT] Alternate version without using add_rewrite_endpoint():

add_filter( 'query_vars', function( $qv ) {
    // This will let you use get_query_var( 'my-gallery' ).
    $qv[] = 'my-gallery';

    // This will let you use get_query_var( 'my-lightbox' ).
    $qv[] = 'my-lightbox';

    return $qv;
} );

add_action( 'init', function() {
    add_rewrite_rule(
        '(.?.+?)/(?:my-gallery/(.+?)/my-lightbox/(\d+)|my-gallery/(.+?)|/?my-lightbox/(\d+))/?$',
        'index.php?pagename=$matches[1]&my-gallery=$matches[2]&my-lightbox=$matches[3]',
        'top'
    );
} );

And I have tested it on these URLs:

  • example.com/nice-page/my-gallery/animals/cats/my-lightbox/1234
  • example.com/nice-page/my-gallery/animals/cats
  • example.com/nice-page/my-lightbox/1234

..where get_query_var( 'my-gallery' ) returns animals/cats (for the first and second URLs) and get_query_var( 'my-lightbox' ) returns 1234 (for the first and third URLs).