Home Data Center Series CloudFlare Tutorial (Ten) Final Chapter: Redirection Function Introduction and Multi-Scenario Configuration Tutorial

Preface

Actually, I originally wanted to end the CF series of tutorials at the ninth part "Zero Trust". After all, in the Book of Changes, nine is called a "big number", representing the largest and most perfect number between heaven and earth, the so-called nine heavens, nine nines returning to one, nine nines returning to eighty-one difficulties and so on. Therefore, ending it with the ninth part is in line with God's will, and it also makes me look very cultured.

However, the various redirection methods provided by CF are indeed very valuable, especially the "dynamic redirection" later introduced by the "redirection rules", which can use function expressions to flexibly construct the URL of the jump target. This, combined with the redirection function of the "page rules" (supports wildcards and wildcard-based capture groups), can create a lot of new tricks. So after thinking about it, I resisted the urge to end at the ninth part and wrote this tenth part as the final chapter of the CF series of tutorials.

However, ending at "ten" is not bad either. In Buddhism, there is a saying of "nine heavens and ten lands" (the ten lands represent the realm of practitioners in Buddhism). Bodhisattvas in the tenth land, "Dharma Cloud Land", already have perfect wisdom, compassion and all skillful means, and are only one step away from becoming a Buddha.

It just so happens that I have studied the "Heart Sutra of Prajna Paramita" and the "Diamond Sutra", and ending with "Ten" is a connection with Buddha.

image.png

Also: I wonder how many people still remember "Nine Heavens, Ten Earths, and Nineteen Demons"?

What is a redirect (HTTP redirect)?

Redirect(Redirect refers to the process of automatically directing users to another specified web page or resource when accessing a web page or resource. Redirection usually occurs in the following scenarios:

  1. URL Changes: When the page address of a website changes, redirection can ensure that the old URL is still accessible and guide users to the new URL to avoid broken links and poor user experience.
  2. Domain Transfer: If the site changes its domain name, redirection can seamlessly transfer the traffic from the old domain name to the new domain name, maintaining the continuity of website access.
  3. Mobile Optimization: Redirect based on user device type (e.g. mobile vs. desktop) to serve optimized version of the page.
  4. SEO Optimization: When page content is merged or deleted, using redirection can concentrate weight, avoid duplicate content, and optimize search engine rankings.

Common redirect types:
301 Redirect(Permanent redirect): This means that the page is permanently moved to a new address. Search engines will transfer the weight of the old address to the new address.
302 Redirect(Temporary redirect): Indicates that the page has been temporarily moved and may return to the old address in the future. Search engines do not pass on weight.

Note: In addition to the commonly used 301 and 302, there are also 303, 307, 308 and special redirects. However, these are rarely encountered by ordinary friends, so they will not be discussed in this article.

CF redirection implementation

There are several different ways to implement CF's redirection feature, the most important of which are: redirection implemented by page rules and redirection rules.

Redirection via page rules

When I talk about Cache Rules (see:Home Data Center Series CloudFlare Tutorial (VI) CF Cache Rules Function Introduction and Detailed Configuration Tutorial), also mentioned page rules, because page rules can also achieve caching (can only be matched based on URLs). In the same way, page rules can also achieve redirection, but they can only be matched based on URLs, and can only achieve 301 or 302 redirection (of course, generally only 301 or 302 is used).

The configuration of page rules is simple.tangwudi.comRedirect access towww.tangwudi.comFor example:

image.png

Although it can only be matched based on URLs, redirection implemented through page rules has unique advantages: it supports*通配符及可以通过"$数字"的捕获组直接把内容传递到重定向URL,如下图:

image.png

还支持通过多个通配符+捕获组来传递参数,如下图:
image.png

However, using the precious page rules with only 3 free places for redirection is a luxury. Even if you have to use it, you have to use it in the most efficient way.

The biggest advantage of using page rules for redirection is that it is in the flow sequence (for a detailed concept of flow sequence, see the article:Cloudflare tutorial series for home data centers (Part 2) Introduction to the functions of each technical node in the CF overall solution traffic sequence) has a very high priority, higher than the "redirection rules" (and "Cache Rules") to be discussed later:

image.png

This is very important and is also the key to achieving complex redirection requirements in a scenario to be discussed later.

Redirection rules

Redirection rules introduction

Since page rules have only 3 free rules and can only match incoming URL requests in a crude way through URLs, they are not suitable as a regular means for daily redirection needs.

As an alternative, CF provides redirect rules as a general means of daily redirection (similar to the relationship between the cache function implemented by page rules and cache rules).

Note: Redirect rules can create simple 301 (permanent redirect) or 302 (temporary redirect) rules (in fact, there are also 303, 307, 308 redirects, which support more types than page rules):

image.png

Types of redirection rules

Redirection rules are divided into two types: "static" and "dynamic". Static redirection and dynamic redirection have different uses and are suitable for different scenarios.

1. Static redirection:

use:Static redirection is suitable for redirecting a fixed URL to another fixed URL (for example, in the previous example,https://tangwudi.comRedirect all visits tohttps://www.tangwudi.com), this redirection rule is static, because it does not change dynamically according to the content and parameters of the request, and if the request contains parameters, such ashttps://tangwudi.com/*Redirect all visits tohttps://www.tangwudi.com/*Static redirection cannot be used.
Typical scenarios: Migrate old pages to new pages, redirect non-preferred domains to preferred domains (the case above), resolve broken links, and avoid 404 errors.

2. Dynamic redirection:

use: Dynamic redirection changes dynamically based on the content of the request, query parameters, user geographic location, etc. For example, you can redirect to a different domain name based on the user's country, or redirect based on certain parameters in the URL.
Typical scenarios: Personalized redirection based on the user's geographic location and device type or browser type, definition of redirection rules based on specific conditions of the request (such as user device, country of origin, etc.), and redirection based on a certain "rule" of the original domain name.

Redirection rule configuration scenario

Static redirection

Common usage scenarios

Let's take the previous example:tangwudi.comRedirect access towww.tangwudi.com, configure the requirement as follows.
In "Rules" - "Redirect Rules" - "Create Rule":

image.png

image.png

Of course, the "when incoming request matches" condition can be very flexible, with many options besides hostname:

image.png

Therefore, compared with "page rules" which only rely on URLs as matching conditions, "redirect rules" can implement much more flexible matching conditions.

Of course, you can't have your cake and eat it too. The matching conditions of redirection rules also have disadvantages: they do not support page rule passing in matching conditions.*Wildcards, so static redirects can't pass parameters through wildcards like page rule redirects: static redirects don't care about the URL passed in.tangwudi.com/No matter how many parameters are followed, you can only jump towww.tangwudi.com/, which is the home page.

Advanced use case: bulk redirection

Because static redirection can only redirect one target URL at a time, if there are a large number of URLs to redirect (for example, the entire site is migrated to another domain name), the default limit of 10 URLs may not be used. Therefore, static redirection also has a separate enhanced function "batch redirection":

image.png

First, follow these steps to create a bulk redirect list:
image.png

image.png

image.png

Then associate the created "bulk redirect list" with the "bulk redirect rule":
image.png

image.png

Common completions:
image.png

Note 1: The bulk redirection list is limited to 5 items.

Note 2: The official format of csv is as follows:

example.com/contacts,https://example.net/contact-us,301,,,, example.com/about,https://example.net/about-us,,FALSE,TRUE,, example.com /docs,https://example.com/draft-docs,302,,TRUE

Note 3: Batch redirection is not the focus of this article, because since the advent of dynamic redirection, no matter how many "regular" redirections there are, a dynamic redirection target URL expression is enough~.

Dynamic redirection

Common usage scenarios: Redirect with URI content

Dynamic redirection is relatively more flexible. Although it still does not support wildcards, it can implement the transmission of URI part parameters through the specified "fields". For example, the "http.request.uri.path" field can implement the URI part./*"The passing effect of wildcard characters.

For example, in the above example, this time I want totangwudi.com/*The access request is redirected intact towww.tangwudi.com/*, then you should use dynamic redirection:

image.png

The redirection destination URL expression is as follows:

concat("https://www.tangwudi.com",http.request.uri.path)
Additional knowledge: Constructing expressions using specified fields and functions
Required fields

In the dynamic redirection expression, you can use the specified fields to automatically match the corresponding content in the incoming URL. For example, suppose the full incoming URL is:https://blog.tangwudi.com/123At this time, if there is an "http.host" field in the expression, the field content is "blog.tangwudi.com"; if there is an "http.request.uri.path" field in the expression, the field content is "/123".

Note: For more fields, see:Dynamic Redirect Fields.

Constructing expressions using functions

When constructing an expression, pay attention to the completeness and correctness of the expression, especially the content expressed by some fields themselves, or the above incoming URLhttps://blog.tangwudi.com/123For example, suppose the expression of the jump target URL constructed by the "concat" function is as follows:

concat("https://www.tangwudi.com/",http.request.uri.path)

Then, the actual effect of the expression is:https://www.tangwudi.com//123, because the content represented by the "http.request.uri.path" field itself has "/", plus the field in double quoteshttps://www.tangwudi.com/The "/" at the end is naturally like this, which is definitely incorrect, so the correct expression needs to remove the "/" in the double quotes, as follows:

concat("https://www.tangwudi.com",http.request.uri.path)

In addition to concat, other commonly used functions include substring, lower, and upper.

Taking the substring function as an example, its meaning is "extract the string starting from the specified position from left to right". The specified position here is counted from 0. For example: substring(http.request.uri.path,3) means indexing the string from position 3. Assuming the content of "http.request.uri.path" is: "/tangwudi/abc", then the output content of the function expression here is "ngwudi/abc".

Note: 0-/, 1-t, 2-a, 3-n.

Advanced use case: Image hosting domain migration

Taking the pictures on my image hosting as an example, suppose I want tohttps://image.tangwudi.com/2023/*.pngRedirect tohttps://abc.tangwudi.com/image/*.png(*The content must be the same), create a new dynamic redirection rule as follows:

image.png

The redirect target URL expression is:

concat("https://abc.tangwudi.com/image/",substring(http.request.uri.path,6))

Note: In this case, redirection using page rules is also simple.

Advanced use case: Domain name redirection based on geographic location

This is an example of my previous deployment method. At that time, I was in the process of migrating from the registered domain name to "tangwudi.com", so during that period, my two domain names were effective at the same time, and all applications had two domain name entrances: one was CF, and the domain name was "*.tangwudi.com"; one is the registered domain name, the domain name is assumed to be"*.tangwudi.xyz".

My requirement at the time was that all applications use a unified entrance for external use."*.tangwudi.com", but make a judgment based on the source of the access request: if the visitor is a domestic IP, redirect to "*.tangwudi.xyz/*"; If the visitor is not from a domestic IP address, the access will proceed normally.

There are 2 requirements in this*Variable: Host name and URI of the third-level domain name Content: Domestic user accessblog.tangwudi.com/123, it redirects toblog.tangwudi.xyz/123;accesswlk.tangwudi.com/12345, it redirects towlk.tangwudi.xyz/12345.

However, this requirement is a bit troublesome. As I mentioned earlier, even for dynamic redirection, the corresponding URI part can only be achieved through the field "http.request.uri.path"/*"Wildcard transmission effect. The host name part "http.host" can only transmit the complete domain name (in this case, blog.tangwudi.com and wlk.tangwudi.com), and cannot transmit only the host name part of the third-level domain name (in this case, blog and wlk).


Originally, if it was just unconditional from*.tangwudi.com/*"Redirect"*.tangwudi.xyz/*", similar requirements can be solved by redirecting a page rule:

image.png

However, to implement redirection based on geographical location such as country, dynamic redirection must be combined with redirection rules.


What should I do? After some thinking: since the jump implemented by page rules only does not support judgment based on address location, the jump part can be realized; and dynamic redirection can realize judgment based on address location, but cannot realize the jump part, then can I combine the two parts to realize this requirement?

It's easy to do with this idea:

  • Step 1: Create a dynamic redirection rule to redirect domestic users to a fictitious URL

Through the target expression, a new URL with a fictitious domain name "abc.tangwudi.com" as the host is constructed to redirect domestic users (the fictitious domain name also needs to add arbitrary address resolution in CF's DNS and enable Xiaocheng Cloud). At the same time, the complete third-level domain name and URI part are combined together as the URI part of the new URL so that the page rule can use wildcards for extraction:

image.png

The URL redirection expression is:

concat("https://abc.tangwudi.com/",http.host,http.request.uri.path)

In the above expression, "http.host" is used to pass the original third-level domain name, and "http.request.uri.path" is used to represent the original URI part. Therefore, if the original access link is "https://blog.tangwudi.com/123", then the new URL formed by this expression is"https://abc.tangwudi.com/blog.tangwudi.com/123".

  • Step 2: Create a page rule to receive domestic users' visits to the fictitious URL, capture relevant information from the fictitious URL to construct the correct access URL, and then send it to the domestic user again in a redirection manner

    Taking advantage of the fact that page rules have a higher priority than cache rules in the traffic sequence (this redirection cannot be cached), we receive the access initiated by the domestic client using a brand new URL, and then use the wildcard capture group mentioned earlier to separate the host name contained in the URI part of the URL from the original URI content, forming the second redirection URL:"https://blog.tangwudi.xyz/123" and sent it to domestic users.

    image.png

  • Step 3: Domestic users use the real URL received the second time"https://blog.tangwudi.xyz/123"To visit.

In this way, after two redirects, I achieved my requirement of redirecting based on geographic location and two variables. However, I don’t recommend using this method under normal circumstances, because this method has a big disadvantage: it jumps back and forth, which gives people a bad impression and makes the website look very unprofessional (personal opinion).

Note: I have only demonstrated two not-too-complex examples here. In practice, there are many more complex requirements. It depends on your understanding and imagination of dynamic redirection expressions and page rule wildcards.

Other redirection methods

In fact, in addition to using page rules and redirection rules to achieve the redirection function, it can also be achieved using workers. However, given the status of workers as a panacea (many functions can be achieved with workers), I will not count it as a serious redirection method. In addition, there is a biggest trouble in using workers to achieve redirection: the worker priority is the lowest in the traffic sequence, so in order to ensure that the access request can reach the worker to achieve redirection, it may be necessary to configure other traffic sequence function modules to cooperate (such as Cache Rules), which is far less worry-free than using redirection rules and page rules to complete the redirection function.

In addition: In the "Conversion Rules", there is also a "Rewrite URL" function:

image.png

If "redirection" is to "openly" tell the user to change the access address, then "rewriting the URL" is to "sneakily" modify the URI part of the access URL (the domain name cannot be changed) without telling the user (the browser access address will not change). However, this does not fit the theme of "redirection" in this article, so I will not say more about it.

Note: Domestic CDN only provides the "Rewrite URL" function (probably because they are afraid that people will do bad things), so when the domain name redirection function is needed, many friends have to use their own VPS to achieve the jump (I used nginx on Tencent Cloud's lightweight server to redirect the registered domain name to www). From this perspective, the various powerful edge network-based redirection functions provided by CF for free are really conscientious, so that we no longer need to configure them on the VPS at every turn (the key is that many people who host their own static websites do not have their own VPS~), and I would like to praise this great man again.

Ending Thoughts

The CF tutorial series is finally finished (from the release of the first part on July 10 to the tenth part on September 2, it took nearly two months). I felt very tired writing each part (including the last part "Redirection" which I originally thought would be easy to write). The key lies in the extensibility of CF-related knowledge: while writing, a concept that I haven't paid much attention to may pop up at any time (if it is just configuration functions and not written as an article, I will not pay attention to these concepts), which results in me having to frequently use "notes" or "additional knowledge" to make temporary explanations, otherwise the readability of the article will be destroyed. In addition, many functions of CF are related to each other, so it is very tiring for me to write each tutorial.

However, despite this, I think it is still worth it. Looking back now, before I wrote the series of tutorials, I had a superficial understanding of the functions described in each tutorial, and only stayed at the level of being able to cope with basic use, so the impression was not deep. For example, the redirection function of this tutorial, I even forgot how to configure it when I migrated from the registered domain name to "tangwudi.com" (after all, I haven't used complex redirection functions since the migration more than half a year ago). I studied for a long time before finding the key point (this is the result of not keeping a written record). Now, after writing this tutorial, even if I forget it in the future, I just need to look at this tutorial and I will remember everything. This is what the saying goes: a good memory is not as good as a bad pen.

However, the content described in the CF series of tutorials is just a summary of the functions that I think are commonly used based on my daily usage habits. There are too many functions that are not mentioned outside the blind spots formed by my "daily usage habits", such as the "point" type "Hotlink protection" function, which can prevent image hotlinking by default (based on referer judgment):

image.png

Or the "D1 database" of the "surface" type, which also has a free plan:
image.png

It's just that my knowledge is limited at present, and I don't know how to get some of the functions I want, so I can only leave regrets in my heart. If I know the method in the future, I will write it in an article, but it will not be in the name of a series of tutorials. After all, I can't destroy the "perfection".

In addition: As the saying goes, "keep your word and do what you say", I have finally finished writing the series of tutorials, and people with obsessive-compulsive disorder can finally sleep peacefully:

image.png

image.png

The content of the blog is original. Please indicate the source when reprinting! For more blog articles, you can go toSitemapUnderstand. The RSS address of the blog is:https://blog.tangwudi.com/feed, welcome to subscribe; if necessary, you can joinTelegram GroupDiscuss the problem together.
No Comments

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠(ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ°Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
Emoticons
Emoji
Little Dinosaur
flower!
Previous
Next
       

This site has disabled the right mouse button and various shortcut keys. The code block content can be copied directly by clicking the copy button in the upper right corner

en_US