Multi-rule matching 301 redirection with CloudFlare Workers

This article was first published on lzcBlog , the original link ishttps://www.lzc256.com/archives/608/ It is recommended to transfer to the original reading for a better experience. This article does not use the Creative Commons copyright template. Please refer to the end of the original text for the reprint agreement.


I changed the domain name of the website to engage in 301 redirection, and I always had problems.

You might say, I use Page Rules, isn't it good? But please note that there are only three Page Rules in the free version, and one domain name is required for forwarding. Workers make 10w requests per day and 30 are free, and setting up routing will not account for any more items. The advantages are obvious.

The tool features are as follows:

  • Multi-rule matching, one Worker handles the forwarding of all domain names
  • Super lightweight
  • The default forwarding type is 301 redirect.
  • In addition to replacing the domain name to achieve forwarding, you can also replace a value in the URL.
  • It can be used for WeChat QQ red prevention, URL forwarding and other purposes.

1. Implementation method

Create a new Workers and paste the following code into the code box.

/* @variable rules
 * @Use: 指定重定向的规则
 * @Usage: 详见 https://www.lzc256.com/archives/608
*/ 
const rules = [{"oldurl":".lzcapp.cn","newurl":".lzc256.com"},{"oldurl":".lzcapp.xyz","newurl":".lzc256.com"}];

async function handleRequest(request) {
  var url = request.url;
  for (var i = 0, l = rules.length; i < l; i++) {
    url = url.replace(rules[i].oldurl, rules[i].newurl);
  }
  return Response.redirect(new URL(url), 301);
}
addEventListener('fetch', async event => {
  event.respondWith(handleRequest(event.request))
});

Change the rules constant as needed, and its type is JSON.

  • Among them, oldurlis the rule that needs to be matched, and newurlis the rule to be replaced
  • oldurlIt can also be new RegExp('xxx')a regular expression of the object type ( ). You can set unlimited rules.

2.rules generation

For students who are not good at JSON, we provide a rules generator. Link: [btnblue href=" https://tools.lzc256.com/lzcCFW301Generator "target="blank"]lzcCFW301Generator[/btnblue]

Guess you like

Origin blog.51cto.com/14906832/2532488
301