Redirect URL to an existing page with query string or #! added on

one way you could do this with an internal WordPress rewrite, which would then set a query var you could check when enqueueing your javascript, and pass that data via localize script.

so first, rewrite rule to intercept requests to gallery/ with something appended, load the page named gallery, and set the query var gallery_id to whatever was in the URL. also we add the gallery_id query var so WordPress knows about it. Make sure to visit permalinks settings page after adding the rewrite, to flush rules and this new rule.

function wpa_gallery_rewrite(){
    add_rewrite_rule(
        'gallery/([^/]+)/?$',
        'index.php?pagename=gallery&gallery_id=$matches[1]',
        'top'
    );
}
add_action( 'init', 'wpa_gallery_rewrite' );

function wpa_gallery_query_var( $query_vars ){
    $query_vars[] = 'gallery_id';
    return $query_vars;
}
add_filter('query_vars', 'wpa_gallery_query_var');

Now when we enqueue our javascript, we can check for that value and set a var which will be added along with the script and available to it.

function wpa_scripts() {
    wp_enqueue_script(
        'wpa_script',
        get_template_directory_uri() . '/js/my_gallery.js',
        array('jquery'),
        null,
        false
    );
    $default_photo = ( get_query_var( 'gallery_id' ) ) ? get_query_var( 'gallery_id' ) : 0;
    wp_localize_script(
        'wpa_script',
        'wpa_data',
        array(
            'default_photo' => $default_photo
        )
    );
}
add_action( 'wp_enqueue_scripts', 'wpa_scripts', 100 );

Now in your javascript, check wpa_data.default_photo to see if it equals 0, or there was a specific photo requested.