如何仅基于URL路径的某一部分实现重定向?
Dynamic Redirect Ignoring Category ID
Hey Peter, nice job getting the basic redirect up and running! To handle that dynamic numeric ID in the category path, we can use either a regular expression (great for pattern matching) or split the path into parts to grab just the post slug. Here are two solid approaches:
Option 1: Regular Expression (Clean Pattern Matching)
This regex will match any path that starts with /category/ followed by one or more numbers, then capture everything after that final slash (your post slug):
// Match paths like /category/123/my-post or /category/9876/another-post const categoryPathRegex = /^\/category\/\d+\/(.+)$/; const pathMatch = window.location.pathname.match(categoryPathRegex); if (pathMatch) { // Extract the captured post slug (e.g., "my-first-post") const postSlug = pathMatch[1]; // Redirect to the new URL with the slug window.location.href = `https://myredirect.net/${postSlug}`; // Optional: Use replace instead of href to avoid adding the old URL to browser history // window.location.replace(`https://myredirect.net/${postSlug}`); }
How this works:
^\/category\/matches the start of the path exactly as/category/\d+matches one or more digits (the dynamic ID you want to ignore)(.+)$captures everything from the final slash to the end of the path (your post slug)
Option 2: Split Path into Parts (More Explicit Structure Check)
If you prefer a more readable approach without regex, split the path into segments and validate the structure:
// Split the path into parts, filtering out empty strings from leading/trailing slashes const pathSegments = window.location.pathname.split('/').filter(segment => segment); // Check if the path has exactly 3 segments: [category, numeric-id, post-slug] if (pathSegments.length === 3 && pathSegments[0] === 'category' && !isNaN(pathSegments[1])) { const postSlug = pathSegments[2]; window.location.href = `https://myredirect.net/${postSlug}`; }
How this works:
split('/')breaks the path into an array (e.g.,/category/83745/my-first-postbecomes["", "category", "83745", "my-first-post"])filter(segment => segment)removes empty strings, leaving["category", "83745", "my-first-post"]- We check that there are 3 segments, the first is "category", the second is a number, then grab the third segment as the slug
Quick Notes:
- Make sure this code runs early in your page load (before any heavy rendering) to avoid unnecessary page content showing up before the redirect
- If you want users to not be able to hit back to the old URL, use
window.location.replace()instead ofwindow.location.href - Both methods will work no matter what the numeric ID is, so you don't have to update the code every time the ID changes
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

