search
HomeOperation and MaintenanceNginxHow to use Nginx web server caddy

    Introduction to Caddy

    Caddy is a powerful, highly scalable web server that has currently gained 38K Stars on GitHub. Caddy is written in Go language and can be used for static resource hosting and reverse proxy.

    Caddy has the following main features:

    • Compared with Nginx’s complex configuration, its original Caddyfile configuration is very simple;

    • The configuration can be dynamically modified through the Admin API it provides;

    • supports automated HTTPS configuration by default, and can automatically apply for HTTPS certificates and configure them;

    • Can be expanded to tens of thousands of sites;

    • can be executed anywhere, with no additional dependencies;

    • is written in Go language , memory security is more guaranteed.

    Installation

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

    Use the following command to install Caddy through the DNF tool. After successful installation, Caddy will be registered as a system service;

    dnf install 'dnf-command(copr)'
    dnf copr enable @caddy/caddy
    dnf install caddy

    Use systemctl status caddy to check the status of Caddy. You can find that Caddy has been registered as a system service. service, but it is not enabled yet.

    How to use Nginx web server caddy

    Usage

    Let’s experience the basic use of Caddy. They are common operations for web servers. You can definitely use them!

    Basic usage

    Let us try to use Caddy to get started, specifying that Caddy runs on the 2015 port and returns the "Hello, world!" message.

    Using the caddy command directly will output the common commands of Caddy. Basically, you will know how to use it by reading the introduction. The common commands are marked;

    How to use Nginx web server caddy

    Use caddy The start command allows the Caddy service to run in the background;

    How to use Nginx web server caddy

    Caddy uses the JSON format configuration file by default. However, since it is more troublesome to write the JSON format configuration, Caddyfile is also provided. Simple configuration form, use the following command to automatically convert Caddyfile into JSON configuration;

    caddy adapter

    We can first create a file named Caddyfile with the following content, and then use caddy adapter to convert it into JSON configuration, Then use caddy reload to make the configuration effective. The configuration will listen to the 2015 port and return Hello, world!;

    :2015
    
    respond "Hello, world!"

    Then we use the curl command to access localhost:2015 and the specified information will be returned;

    How to use Nginx web server caddy

    Of course we can also use the Admin API provided by Caddy to view the configuration information, just use the following command;

    curl localhost:2019/config/

    The current JSON configuration is as follows, if you use JSON configuration directly You need to write the following configuration, using Caddyfile is indeed much more convenient!

    {
    	"apps": {
    		"http": {
    			"servers": {
    				"srv0": {
    					"listen": [":2015"],
    					"routes": [{
    						"handle": [{
    							"body": "Hello, world!",
    							"handler": "static_response"
    						}]
    					}]
    				}
    			}
    		}
    	}
    }

    Basic syntax of Caddyfile

    The following case will use Caddyfile for configuration. We need to understand its syntax. The specific syntax rules of Caddyfile are as follows.

    How to use Nginx web server caddy

    Introduce the keywords in the above picture to help understanding.

    Keyword Explanation Use
    Global options block Server global configuration Can be used to configure whether to enable HTTPS and Admin API, etc.
    Snippet Reusable configuration snippets After definition, it can be referenced through the import keyword
    Site Block Single website configuration Static proxy can be configured through file_server and reverse_proxy Dynamic agents can be configured
    Matcher definition Match definition By default the directive will have a global impact, through which the scope of influence can be specified
    Comment Comment Use the # symbol starting with
    Site address Website address HTTPS is used by default. If you need to enable HTTP, you need to specify the
    Directive directive directive given at the beginning of http:// Caddy’s powerful features

    反向代理

    反向代理就是当请求访问你的代理服务器时,代理服务器会对你的请求进行转发,可以转发到静态的资源路径上去,也可以转发到动态的服务接口上去。我们以代理域名为例,讲解如何进行静态和动态代理。

    静态代理

    静态代理就是将请求代理到不同的静态资源路径上去,这里我们将对docs.macrozheng.com的请求代理到我的文档项目中,对mall.macrozheng.com的请求代理到mall的前端项目中。

    首先我们修改下本机的host文件:

    192.168.3.106 docs.macrozheng.com
    192.168.3.106 mall.macrozheng.com

    然后将我们的文档项目和mall前端项目上传到Caddy的html目录中去,并进行解压操作:

    How to use Nginx web server caddy

    修改Caddyfile文件,使用如下配置,修改完成后使用caddy reload命令刷新配置;

    http://docs.macrozheng.com {
            root * /mydata/caddy/html/docs
            file_server browse
    }
    
    http://mall.macrozheng.com {
            root * /mydata/caddy/html/mall
            file_server browse
    }

    如果你的Caddyfile文件格式不太合格的话,会出现如下警告,直接使用caddy fmt --overwrite格式化并重写配置即可解决;

    How to use Nginx web server caddy

    通过docs.macrozheng.com即可访问部署好的文档项目了:

    How to use Nginx web server caddy

    通过mall.macrozheng.com即可访问到部署好的前端项目了。

    How to use Nginx web server caddy

    动态代理

    动态代理就是把代理服务器的请求转发到另一个服务上去,这里我们将把对api.macrozheng.com的请求代理到演示环境的API服务上去。

    首先我们修改下本机的host文件,添加如下规则

    192.168.3.106 api.macrozheng.com

    修改Caddyfile文件,使用如下配置,修改完成后使用caddy reload命令刷新配置;

    http://api.macrozheng.com {
            reverse_proxy http://admin-api.macrozheng.com
    }

    之后通过api.macrozheng.com/swagger-ui.html即可访问到mall-admin的API文档页面了。

    How to use Nginx web server caddy

    文件压缩

    如果我们的服务器带宽比较低,网站访问速度会很慢,这时我们可以通过让Caddy开启Gzip压缩来提高网站的访问速度。这里我们以mall的前端项目为例来演示下它的提速效果。

    我们需要修改Caddyfile文件,使用encode指令开启Gzip压缩,修改完成后使用caddy reload命令刷新配置;

    http://mall.macrozheng.com {
            root * /mydata/caddy/html/mall
            encode {
                gzip
            }
            file_server browse
    }

    有个比较大的JS文件压缩前是1.7M;

    How to use Nginx web server caddy

    压缩后为544K,访问速度也有很大提示;

    How to use Nginx web server caddy

    另外我们可以看下响应信息,如果有Content-Encoding: gzip这个响应头表明Gzip压缩已经启用了。

    How to use Nginx web server caddy

    地址重写

    有的时候我们的网站更换了域名,但还有用户在使用老的域名访问,这时可以通过Caddy的地址重写功能来让用户跳转到新的域名进行访问。

    我们需要修改Caddyfile文件,使用redir指令重写地址,修改完成后使用caddy reload命令刷新配置;

    http://docs.macrozheng.com {
            redir http://www.macrozheng.com
    }

    此时访问旧域名docs.macrozheng.com会直接跳转到www.macrozheng.com去。

    按目录划分

    有时候我们需要使用同一个域名来访问不同的前端项目,这时候就需要通过子目录来区分前端项目了。

    比如说我们需要按以下路径来访问各个前端项目;

    www.macrozheng.com #访问文档项目
    www.macrozheng.com/admin #访问后台项目
    www.macrozheng.com/app #访问移动端项目

    我们需要修改Caddyfile文件,使用route指令定义路由,修改完成后使用caddy reload命令刷新配置。

    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
            }
    }

    HTTPS

    Caddy能自动支持HTTPS,无需手动配置证书,这就是之前我们在配置域名时需要使用http://开头的原因,要想使用Caddy默认的HTTPS功能,按如下步骤操作即可。

    首先我们需要修改域名的DNS解析,直接在购买域名的网站上设置即可,这里以docs.macrozheng.com域名为例;

    请使用以下命令确认DNS解析记录是否正确,注意所配置的服务器的80和443端口需要在外网中可以正常访问:

    curl "https://cloudflare-dns.com/dns-query?name=docs.macrozheng.com&type=A" \
      -H "accept: application/dns-json"

    修改Caddyfile配置文件,进行如下配置;

    docs.macrozheng.com {
            root * /mydata/caddy/html/docs
            file_server browse
    }

    然后使用caddy run命令启动Caddy服务器即可,是不是非常方便!

    caddy run

    Docker支持

    当然Caddy也是支持使用Docker进行安装使用的,其使用和直接在CentOS上安装基本一致。

    首先使用如下命令下载Caddy的Docker镜像;

    docker pull caddy

    然后在/mydata/caddy/目录下创建Caddyfile配置文件,文件内容如下;

    http://192.168.3.105:80
    
    respond "Hello, world!"

    之后使用如下命令启动caddy服务,这里将宿主机上的Caddyfile配置文件、Caddy的数据目录和网站目录挂载到了容器中;

    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

    之后使用docker exec进入caddy容器内部执行命令;

    docker exec -it caddy /bin/sh

    输入Caddy命令即可操作,之后的操作就和我们直接在CentOS上安装一样了。

    How to use Nginx web server caddy

    The above is the detailed content of How to use Nginx web server caddy. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    The Ultimate Showdown: NGINX vs. ApacheThe Ultimate Showdown: NGINX vs. ApacheApr 18, 2025 am 12:02 AM

    NGINX is suitable for handling high concurrent requests, while Apache is suitable for scenarios where complex configurations and functional extensions are required. 1.NGINX adopts an event-driven, non-blocking architecture, and is suitable for high concurrency environments. 2. Apache adopts process or thread model to provide a rich module ecosystem that is suitable for complex configuration needs.

    NGINX in Action: Examples and Real-World ApplicationsNGINX in Action: Examples and Real-World ApplicationsApr 17, 2025 am 12:18 AM

    NGINX can be used to improve website performance, security, and scalability. 1) As a reverse proxy and load balancer, NGINX can optimize back-end services and share traffic. 2) Through event-driven and asynchronous architecture, NGINX efficiently handles high concurrent connections. 3) Configuration files allow flexible definition of rules, such as static file service and load balancing. 4) Optimization suggestions include enabling Gzip compression, using cache and tuning the worker process.

    NGINX Unit: Supporting Different Programming LanguagesNGINX Unit: Supporting Different Programming LanguagesApr 16, 2025 am 12:15 AM

    NGINXUnit supports multiple programming languages ​​and is implemented through modular design. 1. Loading language module: Load the corresponding module according to the configuration file. 2. Application startup: Execute application code when the calling language runs. 3. Request processing: forward the request to the application instance. 4. Response return: Return the processed response to the client.

    Choosing Between NGINX and Apache: The Right Fit for Your NeedsChoosing Between NGINX and Apache: The Right Fit for Your NeedsApr 15, 2025 am 12:04 AM

    NGINX and Apache have their own advantages and disadvantages and are suitable for different scenarios. 1.NGINX is suitable for high concurrency and low resource consumption scenarios. 2. Apache is suitable for scenarios where complex configurations and rich modules are required. By comparing their core features, performance differences, and best practices, you can help you choose the server software that best suits your needs.

    How to start nginxHow to start nginxApr 14, 2025 pm 01:06 PM

    Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

    How to check whether nginx is startedHow to check whether nginx is startedApr 14, 2025 pm 01:03 PM

    How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

    How to close nginxHow to close nginxApr 14, 2025 pm 01:00 PM

    To shut down the Nginx service, follow these steps: Determine the installation type: Red Hat/CentOS (systemctl status nginx) or Debian/Ubuntu (service nginx status) Stop the service: Red Hat/CentOS (systemctl stop nginx) or Debian/Ubuntu (service nginx stop) Disable automatic startup (optional): Red Hat/CentOS (systemctl disabled nginx) or Debian/Ubuntu (syst

    How to configure nginx in WindowsHow to configure nginx in WindowsApr 14, 2025 pm 12:57 PM

    How to configure Nginx in Windows? Install Nginx and create a virtual host configuration. Modify the main configuration file and include the virtual host configuration. Start or reload Nginx. Test the configuration and view the website. Selectively enable SSL and configure SSL certificates. Selectively set the firewall to allow port 80 and 443 traffic.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    Will R.E.P.O. Have Crossplay?
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.