#38873 closed defect (bug) (fixed)
REST API doesn't match with trailing slash when not using rewrites
Reported by: |
|
Owned by: |
|
---|---|---|---|
Milestone: | 4.7 | Priority: | normal |
Severity: | normal | Version: | |
Component: | REST API | Keywords: | has-patch |
Focuses: | Cc: |
Description (last modified by )
Current, a request to the API with rewrite rules enabled doesn't differentiate URLs with trailing slashes just as http://localhost:8080/wp-json/wp/v2/
vs http://localhost:8080/wp-json/wp/v2
, this seems to be a property to WP_Rewrite / class WP to split off the trailing slash always.
However, when making requests do http://localhost:8080/?rest_route=/wp/v2/
the trailing slash is not stripped, as it doesn't go through the same transformation in class WP
. I think it's safe to always untrailingslash the requested URL in the REST API, for matching purposes.
Attachments (1)
Change History (6)
#2
@
9 years ago
wp-json/wp/v2/posts:
I think this one may depend on the server setup, could be wrong though.
#3
@
9 years ago
- Keywords has-patch added
- Owner set to rmccue
- Status changed from new to reviewing
I'm happy with multiple slashes not working, tbh, as they are different URLs. Stripping the trailing slash seems like a no-brainer though.
#5
@
9 years ago
This hack gets the API console working again on my test sites. I don't think there would be any harm in removing leading slashes from the route as well - it's apparently an easy place to make a mistake.
$ cat wp-content/plugins/fix-rest-api-console.php <?php /** * Plugin Name: Fix the REST API console (`wp-json//` → `wp-json/`) * Author: James Nylen * Plugin URI: https://core.trac.wordpress.org/ticket/38873 */ add_filter( 'rest_pre_dispatch', function( $result, $server, $request ) { $route = $request->get_route(); $route_fixed = preg_replace( '@^/+@', '/', $route ); if ( $route_fixed !== $route ) { $request->set_route( $route_fixed ); } return $result; }, 10, 3 );
Similarly, the official API console is broken on my site due to a duplicated slash in between the REST prefix and the namespace (
wp-json//wp/v2/posts
):Other cases:
//wp-json/wp/v2/posts
: works.//wp-json/wp//v2/posts
: does not work. (Debatable whether it should, aswp/v2
is a valid namespace butwp//v2
is not.)//wp-json/wp/v2//posts
: does not work.