边缘开发者平台
  • 边缘函数
    • 概述
    • 快速指引
    • 操作指引
      • 函数管理
      • Web Debugging
      • 触发配置
      • Environment Variable
    • Runtime APIs
      • addEventListener
      • Cache
      • Cookies
      • Encoding
      • Fetch
      • FetchEvent
      • Headers
      • Request
      • Response
      • Streams
        • ReadableStream
        • ReadableStreamBYOBReader
        • ReadableStreamDefaultReader
        • TransformStream
        • WritableStream
        • WritableStreamDefaultWriter
      • Web Crypto
      • Web standards
      • Images
        • ImageProperties
    • 示例函数
      • Example Overview
      • 301 Redirect
      • Obtaining Client URL Information
      • Customization Based on Client Geo Location
      • Obtaining Client Geo Location Information
      • Batch Redirect
      • 返回 HTML 页面
      • 返回 JSON
      • Fetch 远程资源
      • 请求头鉴权
      • 修改响应头
      • AB 测试
      • 设置 Cookie
      • 基于请求区域重定向
      • Cache API 使用
      • 缓存 POST 请求
      • 流式响应
      • 合并资源流式响应
      • 防篡改校验
      • m3u8 改写与鉴权
      • 图片自适应缩放
      • 图片自适应 WebP
      • 自定义 Referer 限制规则
      • 远程鉴权
      • HMAC 数字签名
      • 自定义下载文件名
      • 获取客户端 IP
    • 最佳实践
      • 通过边缘函数实现自适应图片格式转换
当前内容仅提供英语版本,中文版我们将尽快补充,感谢您的理解。

301 Redirect

This example demonstrates how to use the HTTP 301 status code to automatically and permanently redirect client requests to a preset website address. It is commonly used for permanent site migration or merging.

Sample Code

// Target redirect address
const destinationLocation = 'https://www.example.com';

// HTTP status code, used for permanent redirects
const statusCode = 301;

// Async function used to handle requests
async function handleRequest(request) {
// Return a redirect response with the specified target location and status code.
return Response.redirect(destinationLocation, statusCode);
}

// Add a fetch event listener to intercept requests and respond using the handleRequest function.
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});

Sample Preview

In the address bar of the browser, enter a URL that matches a triggering rule of the edge function to preview the effect of the sample code.


Related References