This article has authorized the use of the public account of the Developer community, including but not limited to editing, marking the original rights and other rights
Written in the beginning
This paper analyzes the network principles by means of text and text analysis and actual combat, to help you to master some network knowledge and understand the basic use of Caddy (see the figure below).
I plan in the last few years will continue to output depth of good articles, if interested in this kind of articles, please also click a concern and support it!
The introduction
Hello, everyone
This article focuses on Caddy, a more front-end friendly Web server from Amway. We will introduce the installation and use of Caddy and explain its principles through graphics.
Caddy is the only Web server that automatically uses HTTPS by default. It can be used to perform cross-domain requests, reverse proxy, static file server, deploy History SPA applications, load balancing, and more. It is very readable, maintainable, and easy to use.
If you’re still wondering what Caddy is for, you can simply think of it as a more front-end friendly nginx.
The reverse proxy
The proxies discussed in this article are restricted to HTTP proxies and no other protocols are involved.
Caddy is a simple and easy to use Web server, reverse proxy is a core function of it. So, before we get to Caddy, let’s talk a little bit about what a reverse proxy is and what it can do for us.
We first to know about the forward agent, forward agent is between the client and server to achieve a proxy server and the client all requests through a proxy server, first by the real server proxy server to request, the request is successful, then by the proxy server will real server response results back to the client.
The classic case of forward proxy is the VPN proxy within an enterprise. During remote development, enterprise employees need to connect to the VPN first, and then connect to the enterprise server through the VPN. By doing this, you can prevent some strange connections and deny all external network connections except the VPN. Only through the VPN can you normally access the company server.
Let’s draw a picture to help you understand what a positive agent is.
On the contrary, reverse proxy is generally on the server side. The network request initiated by the client is first received by the reverse proxy server, and then forwarded to a specific service by the reverse proxy server. In other words, the reverse proxy server determines the target server to which the client will eventually access. Common reverse proxy cases include load balancing and CDN acceleration.
In our actual development, we can use reverse proxies to solve front-end cross-domain problems, deploy front-end services, and so on, and this tutorial focuses on the use of these two features.
Let’s draw a graph to help you understand what a reverse proxy is (see below)
The last word is: the forward proxy hides the real client, and the reverse proxy hides the real server.
The advantage of the Caddy fixings
In our actual development, we can use Caddy to set up reverse proxy servers for cross-domain requests, static file servers, deployment of History SPA applications, load balancing, and so on. The advantage of using Caddy to do this is that we can do it in just a few lines of configuration files. Very simple to use.
In daily development, we usually use Webpack to solve the cross-domain and request forwarding problems in the development environment. The Proxy option of Webpack can solve most of the cross-domain and request forwarding problems, but the support for history routing is poor, and the configuration between the development members in the group may cause conflicts. Incur additional maintenance costs.
These problems can be solved with Nginx, but nginx is complex and not particularly friendly to front end people. In the course of learning nginx we may have drifted away and forgotten that our original purpose was to solve cross-domain and request forwarding problems.
Caddy is written in the Go language, which is cross-platform, has highly readable configuration files, and is more friendly to the front end. The advantages of readability, maintainability, and ease of use are reasons to choose Caddy.
The installationCaddy
With so much introduction, we can almost enter the actual combat part, let’s start from the installation!
Caddy is currently available in two major versions, 1.0 and 2.0. This tutorial is for version 2.0. If you want to use version 1.0, you are advised to check the official documentation for Caddy 1.0.
If you want to see how Caddy works, you can skip the installation section.
Mac
The Mac is perfect for developers, and we welcome them to the Mac family.
First we need to download Caddy, you can also go to the official address to download the latest version.
Since Caddy is written by GO, the files compiled by GO can be executed directly, so after downloading, we can decompress them directly to our own directory, such as ~/bin/ directory. We edit the file using vi ~/.bash_profile and add the following line:
export PATH=~/bin
Copy the code
After adding the global mapping, we use the following command to make our changes take effect
source ~/.bash_profile
Copy the code
Next, let’s input caddy Version to verify whether our installation has taken effect. If it is correct, output the version description of caddy has been installed successfully. (see figure below)
The Windows platform
First we need to download Caddy, you can also go to the official address to download the latest version.
After the download is complete, decompress it to your common directory (the path should not contain Chinese), and then we copy the path of Caddy’s directory (see the following picture).
Then, we use Win + E to evoke the file manager, and right click on my computer and click Properties (see image below).
Then, we’ll go to Advanced and click environment Variables.
Then in the popup window, select the Path column (see picture below).
Then, click new in the popup window and paste the Caddy directory path we copied into it (see the picture below).
Finally, we click OK to save the Settings. We type caddy in the command line, and the installation succeeds! (See picture below)
Linux platform
Use the curl command to download the Caddy installation package as shown below
The curl - OL https://github.com/caddyserver/caddy/releases/download/v2.0.0/caddy_2.0.0_linux_amd64.tar.gzCopy the code
According to their own needs to download the corresponding version of the installation package.
Tar ZXVF caddy_2.0.0_linux_amd64.tar.gz is used to decompress the file. The caddy file after decompressing is an executable file.
Caddy
Using the tutorial
With Caddy installed, let’s learn how to use Caddy.
useCaddy
Solve cross-domain problems
Let’s start by using Caddy to solve one of the most common cross-domain problems on the front end with a simple Demo. In this case, we use FETCH to initiate a network request for a network resource (see figure below)
As you can see from the figure above, after we make a network request using FETCH, we print the result of the request. Now, open the browser and see the results of the request (see the image below).
As you can see from the figure above, our request failed due to cross-domain issues caused by the browser’s same origin policy.
The same origin policy is an important security policy that restricts how documents from one origin can interact with resources from another source, and is constrained when using XMLHttpRequest or FETCH.
To solve this problem, we need the server to return the specified response header (access-control-allow -*), which can be detected by the browser’s same-origin policy.
If you need to configure the response header on the server, then you need to cooperate with the back-end personnel. It is not efficient to push the backend work by the front end, and some back-end personnel may be difficult to cooperate (it may be remote, third-party interface, do not know what cross-domain is…). .
Let’s now use Caddy to solve this problem. We need to solve this cross-domain problem in two simple steps:
- configuration
Caddyfile
(Caddy
Of the configuration file)Caddy
; - configuration
hosts
File;
configurationCaddyfile
Caddyfile is Caddy’s configuration file. Let’s create Caddyfile in the root directory of Demo and add the following lines of code
http://proxy.dev-api-mall.jt-gmall.com {
reverse_proxy http://dev-api-mall.jt-gmall.com {
header_up Host dev-api-mall.jt-gmall.com
header_down Access-Control-Allow-Origin *
header_down Access-Control-Allow-Methods *
header_down Access-Control-Allow-Headers *
}
}
Copy the code
Let’s do a simple parsing of these lines of configuration (see figure below) :
Let’s take a look at what the above lines of core configuration code mean:
Line 1
: the interceptionhttp://proxy.dev-api-mall.jt-gmall.com
This articleurl
For internal logical processing;Line 2
Will:Intercepted request
Forward (reverse proxy) tohttp://dev-api-mall.jt-gmall.com
Our target addressLine 3
: Adds the header field when forwarding a requestHost: dev-api-mall.jt-mall.com
The purpose of this step is to enable the target server to identify the source of the request;4 ~ 6 rows
: Is added when responding to the resultAccess-Control-Allow-*: *
Such as multiple header field information, which can be accessed through the browserThe same-origin policy
Detection;
We can configure Caddyfile with a few lines of nested structure.
configurationhosts
file
After configuring Caddyfile, we change our requested address to http://proxy.dev-api-mall.jt-gmall.com. The code implementation is as follows:
We run caddy on the command line tool using the caddy run –watch command (make sure port 80 is idle when running caddy), caddy will output the following results (see figure below).
Then we open the browser and open http://localhost:3000 (where Demo is running) to see the console output of the request (see below).
As can be seen from the figure above, our request failed. This is because when we access the proxy address (http://proxy.dev-api-mall.jt-gmall.com), the domain name is not registered, which will cause DNS resolution failure and finally cause the request failure.
In this case, you only need to configure the hosts file, point the IP address of the hostname to the host, and add the following record to the hosts file:
127.0.0.1 proxy.dev-api-mall.jt-gmall.com
Copy the code
The hosts file is an operating system file that stores host names and IP addresses in the form of a table and is used to search for host names.
This entry represents the IP address resolved to 127.0.0.1 (local) when accessing proxy.dev-api-mall.jt-gmall.com.
The hosts file configuration methods for different systems are described in the last section of this article.
After configuring the hosts file, we refresh the browser and see the results of our request printed on the console! (See picture below)
As we can see from the figure above, we solved the cross-domain problem by using Caddy’s reverse proxy function, and better simulated the network request in real environment.
The principle of analytic
Let’s go through the process briefly and analyze what Caddy did to help us solve the cross-domain problem.
Our browser is the client, Caddy is both the server and the client, and the target server is the server.
Browser-client
First, we made a request on the client (browser) at http://proxy.dev-api-mall.jt-gmall.com/vegetable/list?page=1&pageSize=20, The browser first resolves the hostname value as proxy.dev-api-mall.jt-gmall.com.
After parsing the hostname, the browser reads the hosts file configuration of the host and checks whether it matches. In this case, it will match the 127.0.0.1 proxy.dev-api-mall.jt-gmall.com rule that we set in the hosts file. Resolve the domain name to the IP address -127.0.0.1, that is, the local address.
After the domain name is resolved, the browser resolves the request port to be empty, the request protocol is HTTP, and then uses the default HTTP port 80 to create a network socket 127.0.0.1:80 with the IP address (as shown below).
Once the network socket is created, the browser creates a TCP connection to the target address 127.0.0.1:80 (the Caddy service we run), encapsulates the request as a standard HTTP protocol, and sends it as a data segment to the server.
Caddy
– Server + client
Our Caddy service runs on local port 80, which corresponds to 127.0.0.1:80. So, the Caddy service receives the TCP connection request. Caddy parses the TCP segment and then parses the HTTP request (see figure below).
As you can see, the source of our request is 127.0.0.1:57721 (IP address is our local IP address, port is the random port used by the browser to initiate the request – the browser client), and the destination is 127.0.0.1:80 (IP address is our local IP address). The port is the running port of Caddy – Caddy server). Our Host request header is proxy.dev-api… (proxy address), the request source (initiator) is http://localhost:3000 (our local service).
Caddy receives the HTTP request and resolves it to HTTP protocol and Host as proxy.dev-api-mall.jt-gmall.com. The combination matches the following configuration rule. (See picture below)
As you can see from the figure above, Caddy begins to process the request after matching the internal rule. Based on configuration rules, Caddy forwards this request to http://dev-api-mall.jt-gmall.com. At this time, Caddy first performs DNS query and port query, combines IP address and port, then establishes TCP connection with the address, and forwards the client’s request to the specified address intact (see the following figure).
As you can see from the figure above, this request is made by Caddy as the client. Our request source is 10.8.71.38:52170 (IP address is the local IP address, port is the random port used by Caddy – Caddy client), destination address is 39.98.164.255:80 (IP address is the target server IP address, The port is the default HTTP port – Target server). Our Host request header is dev-api… (we specify the Host header in Caddyfile), the rest of the header field and the request information are forwarded directly by Caddy to the target server.
The remote server receives the request, processes the request and returns a response. (See picture below)
As we can see from the figure above, the source address of this response is 39.98.164.255:80 (IP address is the server IP address of the request, port is the server port 80 – remote server), and the destination address is 10.8.71.38:52170 (IP address is our local IP address). The port is the random port used by Caddy – Caddy client). The server sends the response to the Caddy client, and after our Caddy client receives the response, the Caddy server processes it.
When processing the response, our Caddy server adds access-control-allow-… to the response according to the Caddyfile configuration. Three header messages, and finally this response is sent to the browser client. (See picture below)
As we can see from the figure above, the source address of this response is 127.0.0.1:80 (the IP address is our local IP address and the port is Caddy’s running port – Caddy server), and the destination address is 127.0.0.1:57721 (the IP address is our local IP address). The port is the random port used by the browser to initiate the request – browser client).
We can see in the response result that we set the header information in Caddyfile access-control-allow -… These three header fields are added to the response result, which can be restricted by the browser’s same origin policy. We can see two Server headers in the response header. One is automatically added by our local Caddy service, and the other may be added by the Caddy Server on the remote Server. Finally, the data is returned and we can see in the browser console that the request succeeded. (See picture below)
As you can see from the figure above, we have solved the cross-domain problem by using Caddy’s reverse proxy function!
Let’s finish with a picture to help you understand the above process. (See picture below)
The image is a little big, I suggest you click to view the original image, so you can see more details.
useCaddy
Set up the reverse proxy server
In this section we’ll set up a reverse proxy server using Caddy, which can easily do the job.
The idea of using Caddy to build a reverse proxy server is similar to the idea of solving cross-domain problems. The reverse_proxy attribute is used in both cases.
What we want to achieve is the effect of reversely proxying the http://www.caddy-test.com domain to our local service http://localhost:3000 when accessing it.
We first added some styles to the http://localhost:3000 service, and the modified effect is shown below
As we can see from the figure above, our service allows us to access a list page using the /list path on the local 3000 port.
At this point we open http://www.caddy-test.com/list (see below)
As you can see from the figure above, this domain name has not been registered, so our DNS query failed!
configurationhosts
file
When we are developing locally, we only need to configure the hosts file and point the IP address of the hostname to the local computer. We add this record in the hosts file:
127.0.0.1 www.caddy-test.com
Copy the code
The hosts file configuration methods for different systems are described in the last section of this article.
This record indicates that IP address 127.0.0.1 (local IP address) is returned when the domain name www.caddy-test.com is matched. After we have configured the hosts file, we open http://www.caddy-test.com/list again (as shown below).
As you can see from the image above, our page is blank. This is because after resolving the domain name and port, the browser ended up accessing the Caddy service at 127.0.0.1:80 (we ran Caddy in the first section), and the Caddy service was not configured to respond to the access to the domain name. Next, we will configure the Caddyfile.
Read more:
If you go to http://www.caddy-test.com:3000/list (specified port) at this point and find the page accessible, It is also possible that the Invalid Host header string was returned (this is because the correct response was intercepted by some of webPack’s built-in security policies, but we have successfully accessed the service).
This is because after specifying the port, the address we access is resolved to 127.0.0.1:3000, directly accessing the service at the specified port.
This approach is neither secure (exposing accessible ports) nor elegant (having a port number is hard to remember).
configurationCaddyfile
We now need to configure our Caddyfile as follows:
http://www.caddy-test.com {
reverse_proxy localhost:3000 {
header_up Host localhost
}
}
Copy the code
Since our command to start Caddy added –watch, our Caddy will automatically restart after detecting the change in Caddyfile.
Now open http://www.caddy-test.com/list again and you can see that our page can be accessed normally (see the picture below)!
As you can see from the figure above, when we access our configured test domain, it shows the page returned by the service we are running on local port 3000. Our reverse proxy configuration is successful!
Read more:
If our domain name is not configured in the hosts file, but is registered with a real domain name registry, then our Caddy service is a “real” reverse proxy server.
Next we parse the Caddyfile configuration file line by line (see figure below).
Let’s break it down line by line:
Line 10
: the interceptionhttp://www.caddy-test.com
This articleurl
For internal logical processing;Line 11
Will:Intercepted request
Forward (reverse proxy) tolocalhost:3000
(our local services)Line 12
: When forwarding a request, the header field is includedHost: localhost
The purpose of this step is to passwebpack
built-inHost
Head safety inspection;
The principle of analytic
In fact, the principle of reverse proxy is the same as solving cross-domain problems, but the remote server address is replaced by the Intranet address, so let’s use a long diagram to explain (see below).
The image is a little big, I suggest you click to view the original image, so you can see more details.
useCaddy
The deployment ofSPA - History
Routing Mode Item
With the reverse proxy covered, let’s take a look at how to use Caddy to deploy a single-page application of the History routing pattern.
Currently, the two front-end routing modes are hash mode and History mode. The hash mode identifies routes by the # symbol in the URL of the address bar, while the History mode identifies routes by the path/XXX.
Using the History routing mode in a single page (SPA) application requires server configuration support, and we can configure the History routing mode through Webpack during development. After we package the application, we can configure our Caddy server to support the HISTORY routing mode SPA application through Caddy.
First, we configured the History routing mode in the SPA application, and then packaged our application with the packaging command NPM run build (packaging varies from technology stack to technology stack). The final directory level of the project looks like this (see figure below).
We built the code in the dist directory, Caddyfile is the same as dist, next we configure Caddyfile, configuration as follows:
http://localhost:3000 {
file_server
root * ./dist
try_files {path} /index.html
}
Copy the code
After configuration is complete, we open the browser, type http://localhost:3000/list, will find that our successful page rendering (see below)!
Let’s take a quick look at these lines of configuration (see figure below)
Let’s break it down line by line:
Line 16
: the interceptionhttp://localhost:3000
This articleurl
For internal logical processing (a real domain name should be configured here when testing or in production);Line 17
: Enables the static file server.Line 18
: The root directory accessed by the static file server is./dist
– indist
Contents outside the folder are not accessible;Row 19
: This line of code is processinghistory
Routing mode key – ifURL
If no static resources are matched, returnindex.html
(to solve404
Problem);
As you can see from the above, it is relatively easy to deploy a single page application with the History routing pattern using Caddy. Here also involves some knowledge of server operation and maintenance, do not expand the first, interested in children’s shoes can be their own to understand.
useCaddy
Load balancing
Using Caddy for load balancing is also based on reverse proxy. We run Demo on three ports respectively (simulating multiple instances running on multiple servers), and the final running effect is as follows:
As you can see from the figure above, we started the same three Demo services, using the title of the site to distinguish them.
To use Caddy for load balancing, you only need to mount multiple services under the same reverse_proxy attribute (see the following figure).
After the configuration is complete, we open the browser, type http://www.caddy-test.com, and refresh several times to see the effect (see below) :
As can be seen from the above three figures, in the process of continuous refresh, Caddy automatically allocates our requests randomly to a service, so as to achieve the effect of load balancing.
Note that the load balancing of actual production environment is much more complex than described in this article, and it is best to understand it if you need it. Load balancing is not the focus of this tutorial and will not be covered.
Platform differenthosts
Configuration file
If you know how to configure the hosts file, you can skip this section
Mac
Mac Hosts file is very simple, run the vi command, as follows:
# Root permission may be required
sudo vi /etc/hosts
Copy the code
Enter the command line and press I to enter the editing mode. After the editing is complete, press Esc to exit the editing mode.
Finally, simultaneously press shift + : and enter wq! You can save your changes.
Linux
Similar to the Mac method, there is no retelling.
Windows
First use the Win + R key to evoke the run input box (as shown below)
Then we type C:\Windows\System32\drivers\etc\hosts and press the OK button (see figure below).
Click the OK button, select notepad to open, and then modify, save can be (may require administrator rights).
conclusion
Finally, we used Caddy for cross-domain requests, reverse proxies, static file servers, deployment of History SPA applications, and load balancing.
As we can see from the example above, Caddy does a good job in terms of readability, maintainability and ease of use. It is easy to learn how to use Caddy.
If it’s only for local development, small to medium applications, then it’s highly recommended that you use Caddy!
If you want to use it for a large, complex project, then it is recommended that you consult the following materials before deciding whether to use it:
- Caddy fixings website
- Caddy fixings community
- Caddy fixings source
One last thing
If you have already seen this, I hope you still click “like” before you go ~
Your “like” is the greatest encouragement to the author, and can also let more people see this article!
If you found this article helpful, please help to light up the Star on Github to encourage!