tencent cloud

URL rewrite based on regular expressions
마지막 업데이트 시간:2025-01-15 10:43:38
URL rewrite based on regular expressions
마지막 업데이트 시간: 2025-01-15 10:43:38
This example captures incoming HTTP requests, matches them using regular expressions according to the URL path, and implements URL rewriting to access the index.html page when specific content is matched. It is applicable for any request under the specified directory to be uniformly rewritten to access the homepage (usually index.html), allowing different page requests to be handled through front-end routing.

Sample code

async function handleEvent(event) {
const { request } = event;
const urlInfo = new URL(request.url);
// Regular expression matches /test/ followed by 1 or 2 path segments that are not slashes
const regexp = /^\\/test\\/([^\\/]+)(?:\\/([^\\/]+))?\\/?$/;
// Check if the path matches the regular expression
if (regexp.test(urlInfo.pathname)) {
const matches = urlInfo.pathname.match(regexp);
let newPathname = '/test/';
// Construct a new pathname, which may be one or two according to the number of matched path segments
newPathname += matches[1]; // The first path segment
if (matches[2]) {
newPathname += '/' + matches[2]; // The second path segment, if any
}
// Ensure it ends with index.html
newPathname += '/index.html';
// Update the pathname of URLInfo
urlInfo.pathname = newPathname;
}
// Make a request using the updated URLInfo
const response = await fetch(urlInfo.toString(), {
method: request.method,
headers: request.headers,
redirect: 'manual',
body: request.body,
});
// return the response to the event
return event.respondWith(response);
}

// call the handleEvent function for each fetch event
addEventListener('fetch', (event) => {
handleEvent(event);
});

Sample Preview

1. Enter the URL matching the edge function trigger rules in the browser address bar, carry /test/segment1 in the path to achieve dynamic rewriting access https://www.example.com/test/segment1/index.html



2. Enter the URL matching the edge function trigger rules in the browser address bar, carry /test/segment1/segment2 in the path to achieve dynamic rewriting access https://www.example.com/test/segment1/segment2/index.html



3. Enter the URL matching the edge function trigger rules in the browser address bar, carry non-regular matching content in the path, such as: /test/test1




Related References

문제 해결에 도움이 되었나요?
더 자세한 내용은 문의하기 또는 티켓 제출 을 통해 문의할 수 있습니다.
아니오

피드백