Nginx is a very popular Web server with 16K+Star on Github and we often use it for static resource hosting or reverse proxy. Recently, a new Web server Caddy was discovered, with more stars than Nginx and 38K+Star. I tried Caddy and found it to be much more elegant and powerful than Nginx. I recommend it!

SpringBoot e-commerce project mall (50K + STAR) address: github.com/macrozheng/…

Caddy fixings profile

Caddy is a powerful, scalable Web server, currently on Github 38K+Star. Caddy is written in the Go language and can be used for static resource hosting and reverse proxies.

Caddy has the following key features:

  • Contrast Nginx’s complex configuration with its originalCaddyfileThe configuration is very simple;
  • Can be provided through itAdmin APIDynamically modify the configuration;
  • By default, you can automatically apply for and configure HTTPS certificates.
  • Scalable to tens of thousands of sites;
  • Can execute anywhere with no additional dependencies;
  • Use Go language, memory security is more guaranteed.

The installation

First of all, we can directly install Caddy on CentOS 8, using DNF tool is undoubtedly the easiest installation, Docker installation will be introduced later.

  • Use the following command to install Caddy using the DNF tool. After the installation is successful, Caddy will be registered as a system service.
dnf install 'dnf-command(copr)'
dnf copr enable @caddy/caddy
dnf install caddy
Copy the code
  • usesystemctl status caddyLooking at Caddy’s status, you can see that Caddy is registered as a system service, but not yet enabled.

use

Let’s experience the basic use of Caddy, for the Web server are common operations, you must be able to use up!

The basic use

Let’s get started with Caddy. Let Caddy run on port 2015 and return Hello, world! .

  • Direct use ofcaddyCommand will output Caddy common command, basically read the introduction to know how to use, marked is common command;

  • usecaddy startCommand to run the Caddy service in the background;

  • Caddy uses JSON configuration files by default, but JOSN configuration files are provided because it is cumbersome to writeCaddyfileThis more concise form of configuration can be automatically changed by using the following commandCaddyfileConvert to JSON configuration;
caddy adapter
Copy the code
  • We can create a name calledCaddyfileFile, file content below, then usecaddy adapterConvert it to a JSON configuration and use it againcaddy reloadTo enable the configuration to listen2015Port and returnHello, world!;
:2015

respond "Hello, world!"
Copy the code
  • Then we use the curl command to accesslocalhost:2015, returns the specified information;

  • Of course we can also use Caddy’sAdmin APITo view the configuration information, run the following command:
curl localhost:2019/config/
Copy the code
  • The current JSON configuration is as follows. If you directly use JSON configuration, you need to write the following configurationCaddyfileIt’s really convenient!
{
   "apps": {
      "http": {
         "servers": {
            "srv0": {
               "listen": [": 2015"]."routes": [{
                  "handle": [{
                     "body": "Hello, world!"."handler": "static_response"}]}]}}}}}Copy the code

CaddyfileThe basic grammar

  • The following example will be usedCaddyfileWe need to know the syntax,CaddyfileThe specific grammar rules of “.

  • Introduce the keywords in the figure above to help you understand.
The keyword explain use
Global options block Server Global Configuration You can configure whether to enable HTTPS and the Admin API
Snippet Configuration fragments that can be reused After the definition is approvedimportKeyword reference
Site Block Single Site Configuration throughfile_serverStatic proxy can be configured throughreverse_proxyDynamic proxies can be configured
Matcher definition Match the definition By default, directives have global impact, which allows you to specify the scope of influence
Comment annotation use#Symbol at the beginning
Site address Web site address HTTPS is used by default. If you want to enable HTTP, specify this parameterhttp://At the beginning
Directive instruction The instructions give Caddy great power

The reverse proxy

Reverse proxy means that when a request is made to your proxy server, the proxy server forwards the request, either to a static resource path or to a dynamic service interface. Let’s take the domain name proxy as an example to talk about how to carry out static proxy and dynamic proxy.

Static agent

Static proxy is to delegate requests to different static resource paths. Here we delegate requests for docs.macrozheng.com to my documents project and requests for Mall.macrozheng.com to mall’s front end project.

  • First let’s modify the local host file:
192.168.3.106 docs.macrozheng.com
192.168.3.106 mall.macrozheng.com
Copy the code
  • Then upload our document project and mall front end project to Caddy’s HTML directory and unzip it:

  • Modify theCaddyfileFile, use the following configuration, after the modification is completecaddy reloadCommand to refresh the configuration.
http://docs.macrozheng.com {
        root * /mydata/caddy/html/docs
        file_server browse
}

http://mall.macrozheng.com {
        root * /mydata/caddy/html/mall
        file_server browse
}
Copy the code
  • If you have aCaddyfileIf the file format is not qualified, the following warning will appear. Use it directlycaddy fmt --overwriteFormat and rewrite the configuration.

  • throughdocs.macrozheng.comYou can access the deployed document project:

  • throughmall.macrozheng.comYou can access the deployed front-end project.

A dynamic proxy

Dynamic proxy is a proxy server that forwards requests to another service. Here we will proxy requests to api.macrozheng.com to the demo environment API service.

  • First let’s modify the host file and add the following rules:
192.168.3.106 api.macrozheng.com
Copy the code
  • Modify theCaddyfileFile, use the following configuration, after the modification is completecaddy reloadCommand to refresh the configuration.
http://api.macrozheng.com {
        reverse_proxy http://admin-api.macrozheng.com
}
Copy the code
  • After throughapi.macrozheng.com/swagger-ui.htmlAccess tomall-adminAPI documentation page.

File compression

If our server bandwidth is low and the site is slow to access, we can speed up the site by having Caddy enable Gzip compression. Here we use mall’s front end project as an example to demonstrate its speed up effect.

  • We need to modifyCaddyfileFile, usingencodeCommand to enable Gzip compression, use after modificationcaddy reloadCommand to refresh the configuration.
http://mall.macrozheng.com {
        root * /mydata/caddy/html/mall
        encode {
            gzip
        }
        file_server browse
}
Copy the code
  • There is a relatively large JS file before compression is1.7 M;

  • Compressed for544K, access speed also has great hints;

  • And we can look at the response information, if there isContent-Encoding: gzipThis response header indicates that Gzip compression is enabled.

Address rewrite

Sometimes we change the domain name of our website, but there are still users using the old domain name. In this case, we can use the address rewriting function of Caddy to let users jump to the new domain name for access.

  • We need to modifyCaddyfileFile, usingredirInstruction rewrite address, used after modificationcaddy reloadCommand to refresh the configuration.
http://docs.macrozheng.com {
        redir http://www.macrozheng.com
}
Copy the code
  • Access the old domain at this pointdocs.macrozheng.comIt jumps directly towww.macrozheng.comGo to.

By directory

Sometimes we need to use the same domain name to access different front-end projects. In this case, we need to distinguish front-end projects by subdirectory.

  • For example, we need to access each front-end project by following the following path;
www.macrozheng.com # Access documentation project www.macrozheng.com/admin # Access background project www.macrozheng.com/app # Access mobile projectCopy the code
  • We need to modifyCaddyfileFile, usingrouteThe command defines the route and is used after modificationcaddy reloadCommand to refresh the configuration.
http://www.macrozheng.com {
        route /admin/* {
                uri strip_prefix /admin
                file_server {
                        root /mydata/caddy/html/admin
                }
        }
        route /app/* {
                uri strip_prefix /app
                file_server {
                        root /mydata/caddy/html/app
                }
        }
        file_server * {
                root /mydata/caddy/html/www
        }
}
Copy the code

HTTPS

Caddy automatically supports HTTPS and does not require manual certificate configuration. This is why we used http:// to start the domain name configuration. To use Caddy’s default HTTPS function, follow the steps below.

  • First of all, we need to modify the DNS resolution of the domain name, which can be set directly on the website where the domain name is purchased. Here we take docs.macrozheng.com as an example.

  • Then run the following command to check whether the DNS resolution record is correct. Ensure that ports 80 and 443 of the server can be accessed from the Internet.

curl "https://cloudflare-dns.com/dns-query?name=docs.macrozheng.com&type=A" \
  -H "accept: application/dns-json"
Copy the code
  • Modify theCaddyfileConfiguration file, perform the following configuration;
docs.macrozheng.com {
        root * /mydata/caddy/html/docs
        file_server browse
}
Copy the code
  • Then use thecaddy runCommand to start Caddy server, is not very convenient!
caddy run
Copy the code

Docker support

Of course, Caddy also supports the use of Docker installation, which is basically the same as the use of direct CentOS installation.

  • First use the following command to download Caddy Docker image;
docker pull caddy
Copy the code
  • Then, in/mydata/caddy/Directory creationCaddyfileThe configuration file contains the following contents:
http://192.168.3.105:80

respond "Hello, world!"
Copy the code
  • Then start the caddy service using the following command, which will host theCaddyfileConfiguration files, Caddy’s data directory, and website directory are mounted into the container;
docker run -p 80:80 -p 443:443 --name caddy \
    -v /mydata/caddy/Caddyfile:/etc/caddy/Caddyfile \
    -v /mydata/caddy/data:/data \
    -v /mydata/caddy/html:/usr/share/caddy \
    -d caddy
Copy the code
  • After usingdocker execEnter the caddy container to execute the command;
docker exec -it caddy /bin/sh
Copy the code
  • Enter the Caddy command to operate, and then the operation is the same as we directly install on CentOS.

conclusion

Today I experienced a Caddy, its powerful command function, let us achieve a variety of functions without unnecessary configuration, it is really very elegant to use! In particular, it can automatically configure HTTPS, very good! Nginx does almost everything Caddy does. If you look at the Nginx tutorial, you’ll see how elegant Caddy is.

If you want to learn more about SpringBoot, you can try the full SpringBoot program (50K+Star) at github.com/macrozheng/…

The resources

  • Project address: github.com/caddyserver…
  • Official document: caddyServer.com/