How to use Nginx web server caddy
May 30, 2023 pm 12:19 PMIntroduction 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.
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;
Use caddy The start command allows the Caddy service to run in the background;
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;
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.
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 |
反向代理
反向代理就是當請求訪問你的代理服務器時,代理服務器會對你的請求進行轉(zhuǎn)發(fā),可以轉(zhuǎn)發(fā)到靜態(tài)的資源路徑上去,也可以轉(zhuǎn)發(fā)到動態(tài)的服務接口上去。我們以代理域名為例,講解如何進行靜態(tài)和動態(tài)代理。
靜態(tài)代理
靜態(tài)代理就是將請求代理到不同的靜態(tài)資源路徑上去,這里我們將對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目錄中去,并進行解壓操作:
修改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文件格式不太合格的話,會出現(xiàn)如下警告,直接使用caddy fmt --overwrite格式化并重寫配置即可解決;
通過docs.macrozheng.com即可訪問部署好的文檔項目了:
通過mall.macrozheng.com即可訪問到部署好的前端項目了。
動態(tài)代理
動態(tài)代理就是把代理服務器的請求轉(zhuǎn)發(fā)到另一個服務上去,這里我們將把對api.macrozheng.com的請求代理到演示環(huán)境的API服務上去。
首先我們修改下本機的host文件,添加如下規(guī)則
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文檔頁面了。
文件壓縮
如果我們的服務器帶寬比較低,網(wǎng)站訪問速度會很慢,這時我們可以通過讓Caddy開啟Gzip壓縮來提高網(wǎng)站的訪問速度。這里我們以mall的前端項目為例來演示下它的提速效果。
我們需要修改Caddyfile文件,使用encode指令開啟Gzip壓縮,修改完成后使用caddy reload命令刷新配置;
http://mall.macrozheng.com { root * /mydata/caddy/html/mall encode { gzip } file_server browse }
有個比較大的JS文件壓縮前是1.7M;
壓縮后為544K,訪問速度也有很大提示;
另外我們可以看下響應信息,如果有Content-Encoding: gzip這個響應頭表明Gzip壓縮已經(jīng)啟用了。
地址重寫
有的時候我們的網(wǎng)站更換了域名,但還有用戶在使用老的域名訪問,這時可以通過Caddy的地址重寫功能來讓用戶跳轉(zhuǎn)到新的域名進行訪問。
我們需要修改Caddyfile文件,使用redir指令重寫地址,修改完成后使用caddy reload命令刷新配置;
http://docs.macrozheng.com { redir http://www.macrozheng.com }
此時訪問舊域名docs.macrozheng.com會直接跳轉(zhuǎn)到www.macrozheng.com去。
按目錄劃分
有時候我們需要使用同一個域名來訪問不同的前端項目,這時候就需要通過子目錄來區(qū)分前端項目了。
比如說我們需要按以下路徑來訪問各個前端項目;
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解析,直接在購買域名的網(wǎng)站上設置即可,這里以docs.macrozheng.com域名為例;
請使用以下命令確認DNS解析記錄是否正確,注意所配置的服務器的80和443端口需要在外網(wǎng)中可以正常訪問:
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/目錄下創(chuàng)建Caddyfile配置文件,文件內(nèi)容如下;
http://192.168.3.105:80 respond "Hello, world!"
之后使用如下命令啟動caddy服務,這里將宿主機上的Caddyfile配置文件、Caddy的數(shù)據(jù)目錄和網(wǎng)站目錄掛載到了容器中;
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容器內(nèi)部執(zhí)行命令;
docker exec -it caddy /bin/sh
輸入Caddy命令即可操作,之后的操作就和我們直接在CentOS上安裝一樣了。
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

NGINX is more suitable for handling high concurrent connections, while Apache is more suitable for scenarios where complex configurations and module extensions are required. 1.NGINX is known for its high performance and low resource consumption, and is suitable for high concurrency. 2.Apache is known for its stability and rich module extensions, which are suitable for complex configuration needs.

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

PHP code can be executed in many ways: 1. Use the command line to directly enter the "php file name" to execute the script; 2. Put the file into the document root directory and access it through the browser through the web server; 3. Run it in the IDE and use the built-in debugging tool; 4. Use the online PHP sandbox or code execution platform for testing.

Understanding Nginx's configuration file path and initial settings is very important because it is the first step in optimizing and managing a web server. 1) The configuration file path is usually /etc/nginx/nginx.conf. The syntax can be found and tested using the nginx-t command. 2) The initial settings include global settings (such as user, worker_processes) and HTTP settings (such as include, log_format). These settings allow customization and extension according to requirements. Incorrect configuration may lead to performance issues and security vulnerabilities.

Linux system restricts user resources through the ulimit command to prevent excessive use of resources. 1.ulimit is a built-in shell command that can limit the number of file descriptors (-n), memory size (-v), thread count (-u), etc., which are divided into soft limit (current effective value) and hard limit (maximum upper limit). 2. Use the ulimit command directly for temporary modification, such as ulimit-n2048, but it is only valid for the current session. 3. For permanent effect, you need to modify /etc/security/limits.conf and PAM configuration files, and add sessionrequiredpam_limits.so. 4. The systemd service needs to set Lim in the unit file

When configuring Nginx on Debian system, the following are some practical tips: The basic structure of the configuration file global settings: Define behavioral parameters that affect the entire Nginx service, such as the number of worker threads and the permissions of running users. Event handling part: Deciding how Nginx deals with network connections is a key configuration for improving performance. HTTP service part: contains a large number of settings related to HTTP service, and can embed multiple servers and location blocks. Core configuration options worker_connections: Define the maximum number of connections that each worker thread can handle, usually set to 1024. multi_accept: Activate the multi-connection reception mode and enhance the ability of concurrent processing. s

NGINXserveswebcontentandactsasareverseproxy,loadbalancer,andmore.1)ItefficientlyservesstaticcontentlikeHTMLandimages.2)Itfunctionsasareverseproxyandloadbalancer,distributingtrafficacrossservers.3)NGINXenhancesperformancethroughcaching.4)Itofferssecur

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.
