Archives 四月 2019

v2ray配置WebSocket+TLS+Web+CDN(支持Nginx或Caddy转发)

安装

这里我用的官方原版一键脚本

bash <(curl -L -s https://install.direct/go.sh)

安装之后,正常情况下v2ray自动启动

服务器配置

这次 TLS 的配置将写入 Nginx / Caddy / Apache 配置中,由这些软件来监听 443 端口(443 比较常用,并非 443 不可),然后将流量转发到 V2Ray 的 WebSocket 所监听的内网端口(本例是 12345),V2Ray 服务器端不需要配置 TLS
服务器 V2Ray 配置

{
  "inbounds": [
    {
      "port": 12345,
      "listen":"127.0.0.1",//只监听 127.0.0.1,避免除本机外的机器探测到开放了 12345 端口
      "protocol": "vmess",
      "settings": {
        "clients": [
          {
            "id": "b370881d-6324-4d53-ad4f-8cda48b13578",
            "alterId": 64
          }
        ]
      },
      "streamSettings": {
        "network": "ws",
        "wsSettings": {
        "path": "/ws"
        }
      }
    }
  ],
  "outbounds": [
    {
      "protocol": "freedom",
      "settings": {}
    }
  ]
}

Nginx 配置

server {
  listen  443 ssl;
  ssl on;
  ssl_certificate       /etc/v2ray/v2ray.crt;
  ssl_certificate_key   /etc/v2ray/v2ray.key;   //这俩证书路径改成你的
  ssl_protocols         TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers           HIGH:!aNULL:!MD5;
  server_name           mydomain.me;  //域名改成你的
        location /ws { # 与 V2Ray 配置中的 path 保持一致
        proxy_redirect off;
        proxy_pass http://127.0.0.1:12345;#假设WebSocket监听在环回地址的12345端口上
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        }
}

如果用了宝塔自动申请证书,那么只需并在Nginx里最后一个 }前面填入

         location /ws {   #/ws为v2ray路径,随便填写比如/v2ray/
             proxy_redirect off;
             proxy_pass http://127.0.0.1:12345; #修改自己v2ray服务端口
             proxy_http_version 1.1;
             proxy_set_header Upgrade $http_upgrade;
             proxy_set_header Connection "upgrade";
             proxy_set_header Host $http_host;            
          }

Caddy 配置

#因为 Caddy 会自动申请证书并自动更新,所以使用 Caddy 不用指定证书、密钥。
mydomain.me
{
  log ./caddy.log
  proxy /ws localhost:12345 {
    websocket
    header_upstream -Origin
  }
}

如果不成功,配置上邮箱自动签证书

mydomain.me {
    tls [email protected] //邮箱改成你的
    gzip
timeouts none
    proxy /ws 127.0.0.1:12345 {
        without /ws
        websocket
    }
}

或者用caddy直接搞个反代

mydomain.me {
    tls [email protected]
    gzip
timeouts none
    proxy / https://www.centos.org {    //把这个网址换成你想反代的地址
        without /ws
    }
    proxy /ws 127.0.0.1:12345 {
        without /ws
        websocket
    }
}

Nginx一样可以配置反代,可以用宝塔面板很方便,就不介绍了。

CND

当然用CloudFlare了,其实实现TLS最简单的办法也是CloudFlare
注意:
1、确保域名已经可以在 Cloudflare 正常使用
2、在 Cloudflare 的 Overview 选项卡可以查看域名状态,请确保为激活状态,即是: Status: Active
3、在 DNS 选项卡那边添加一个 A 记录的域名解析,假设你的域名是 mydomain.me,并且想要使用 vpn.mydomain.me 作为翻墙的域名
那么在 DNS 那里配置,Name 写 vpn,IPv4 address 写你的小鸡的 IP,务必把云朵点灰,然后选择 Add Record 来添加解析记录即可
(如果你已经添加域名解析,请务必把云朵点灰,即是 DNS only)
4、当你的V2ray搭建好,nginx或者caddy配置好后,设置 Crypto 和 开启中转

确保 Cloudflare 的 Crypto 选项卡的 SSL 为 Full
并且请确保 SSL 选项卡有显示 Universal SSL Status Active Certificate 这样的字眼,如果你的 SSL 选项卡没有显示这个,不要急,只是在申请证书,24 小时内可以搞定。

5、在 DNS 选项卡那里,把刚才点灰的那个云朵图标,点亮它,一定要点亮一定要点亮一定要点亮

云朵图标务必为橙色状态,即是 DNS and HTTP proxy(CDN)

V2Ray WebSocket 传输协议实现外网访问

感谢一下大神给霜天指明道路。

  1. 使用 Cloudflare 中转 V2Ray WebSocket 的流量来避免 IP 被墙  https://233blog.com/post/22/
  2. 官方指导说明:https://www.v2ray.com
  3. 另一个配置指南:https://toutyrater.github.io/
  4. Github官方地址:https://github.com/v2ray/v2ray-core

本文将使用最简单的方式,搭建,原始教程:https://233blog.com/post/22/

好了,进入今天的正题吧。

起因:GFW全面升级,写了一篇帖子,长沙SEO霜天教大家五分钟安装和配置v2ray访问谷歌。写的时候没想过要拯救下搬瓦工的用户。

经过:大部分的朋友都是搬瓦工因为ip被墙了,问霜天如何解决问题,毕竟钱还是钱。霜天也是老规矩没办法、没时间、没精力一一回复。

结果:一篇帖子,从零开始。送给有智商、有悟性、有能力的你。

准备工具:

1、服务器

2、域名(Cloudflare能正常使用)

3、Cloudflare 正常使用

爬文太麻烦?没关系,霜体开通在线服务功能,200美金一次。

一、域名问题

域名的问题,最好自己去买一个,购买网址:https://sg.godaddy.com/zh/

这个购买一个域名,大约7块钱。做戏做全套吧。为此也浪费几块钱,给大家做个全套服务。

先点击,添加到购物车,然后点击进入购物车。

这个时候,他们会推荐你购买隐私保护盾和服务器,都选择不用就好了。直接点击添加这些选项到购物车。然后点击支付宝支付,点击保存。

打开你的新页面,购买。

然后,找到我的域名。

找到购买域名的三个点,其他的东西不要点。土豪任性请随意。

进入域名设置:找到其他设置。点击管理DNS

看到记录和域名服务器了吗?这两个板块是我们需要修改的地方。

先注册一个 cloudflare 账户,网址:https://www.cloudflare.com/,当然,您可以选择付费帮注册(200美金一次)

注册成功后,添加你购买的网址。如图下:

接下来是购买主机、配置cf、配置服务器。

二、购买主机

购买链接:https://www.vultr.com

这里有时候有些异常,会提示输入验证码 ( 如下图 ) ,如果有就按照提示再次输入,没有就跳到下一步

输入“邮箱”“密码”“验证码”,点击“创建账户”按钮

点击创建账户后,会跳转到登陆页面(如下图),这时还无法登陆,需要去邮箱验证账户

打开邮箱,验证账户(如下图)

登陆后就到付款页面了。已经有显示25美元的promo。

新用户请先注册:https://www.vultr.com

新注册Vultr账户,充值5美元赠送25美元余额(支持支付宝)>>>:https://www.vultr.com

然后充值,

选择合适的充值方式

充值完毕后我们点击右上角的那个加号来购买我们的VPS。

最好用支付宝支付

最好用支付宝支付

最好用支付宝支付

如果你不用支付宝,用银行卡,那么就需要按照如下图填写,如果使用支付宝的,请跳过。

然后就是选择服务器位置、系统及配置,亚洲的话推荐新加坡、东京,美国可以用洛杉矶,其他的地方也可以尝试。

欧洲不建议选,服务器位置、你所在地区和使用的运营商决定了远程连接的延时,大家可以到网上了解一下选择最优解;

霜天呢,无谓不在乎速度,所以,使用New York的位置,Debian X8 64 的配置。

进入控制台就能看到我们刚买的服务器了,几分钟后系统装完我们就点击进入详情页面查看。

购买了域名后,将域名解析到服务器。

设置成功的话是如图下:

只需要修改 pointe to xxx.xxx.xxx.xxx 这个就行了。同样,我们域名处也需要设置,设置如下

接下来修改DNS。

修改成如图下:

改成这样子就行了。接下来我们做另外一件事情。

然后,变成如图下!!!(不要再来问,不然你等下安装会安装不上去)

然后,变成如图下!!!(不要再来问,不然你等下安装会安装不上去)

然后,变成如图下!!!(不要再来问,不然你等下安装会安装不上去)

第三步:连接服务器

接下来呢,使用工具 xshell 5 ,下载链接地址是 :xshell-5下载地址

登陆服务器:

将你购买服务器的IP地址复制到这里

然后,点击确定。

到达如图下的界面:我们就可以输入代码:

下面霜天以Debian 8 x64 系统为例,安装V2ray。

(旁边没有window笔记本,我就用mac笔记本代替吧,先登录,代码都是一样的。)

如果你并没有使用本站提供的 V2Ray 一键安装脚本来安装 V2Ray。那么现在开始使用吧,最好用的 V2Ray 安装脚本,保证你满意。使用 root 用户输入下面命令安装或卸载

bash <(curl -s -L https://233blog.com/v2ray.sh)
  • 如果提示 curl: command not found ,那是因为你的服务器没装 Curl
  • ubuntu/debian 系统安装 Curl 方法: apt-get update -y && apt-get install curl -y
  • centos 系统安装 Curl 方法: yum update -y && yum install curl -y
  • 安装好 curl 之后就能安装脚本了

一路回车下去。

这样就算安装完成了。

如果你的域名没有正确解析,安装会失败,解析相关看上面的

添加域名解析安装完成后会展示 V2Ray 的配置信息,并且会询问是否生成二维码等,不用管它,直接回车然后输入 v2ray status 查看一下运行状态,请确保 V2Ray 和 Caddy 都在运行。如图下

接下来进行测试,我用手机给大家做个测试吧。

测试成功。接下来返回 cloudflare ,打开

确保 Cloudflare 的 Crypto 选项卡的 SSL 为 Full,Status 要为 Active 。

然后在 DNS 选项卡那里,把刚才点灰的那个云朵图标,点亮它,一定要点亮一定要点亮一定要点亮云朵图标务必为橙色状态,即是 DNS and HTTP proxy(CDN)

最后:

很早之前就出过v2ray的各种教程,这里呢,重新放一次:

V2Ray iPhone、ipad、IOS常用客户端及V2Ray IOS使用教程

V2Ray Android (安卓)使用教程之 v2rayNG

Mac V2Ray 苹果系统使用教程 V2RayX

V2Ray window下使用教程,V2RayN使用教程

上传window配置图

上传iPhone 配置图:

How To Install WordPress with Caddy on CentOS 7

Introduction

WordPress is a popular content management system (CMS). It can be used to set up blogs and websites quickly and easily, and almost all of its administration is possible through a web interface.

In most cases, WordPress is installed using a LAMP or LEMP stack (i.e. using either Apache or Nginx as a web server). In this guide, we’ll set up WordPress with Caddy instead. Caddy is a new web server quickly gaining popularity for its wide array of unique features, like HTTP/2 support and automatic TLS encryption with Let’s Encrypt, a popular free certificate provider.

In this tutorial, you will install and configure WordPress backed by Caddy.

Prerequisites

To follow this tutorial, you will need:

Step 1 — Installing PHP

In order to run WordPress, you need a web server, a MySQL database, and the PHP scripting language. You already have the Caddy webserver and a MySQL database installed from the prerequisites, so the last requirement is to install PHP.

First, make sure your packages are up to date.

sudo yum update

Install PHP and the PHP extensions WordPress depends on, like support for MySQL, curl, XML, and multi-byte strings.

sudo yum install php php-fpm php-mysql php-curl php-gd php-mbstring php-mcrypt php-xml php-xmlrpc

Once the installation finishes, you can verify that PHP was installed correctly by checking the PHP’s version.

php -v

You’ll see output similar to this, which displays PHP’s version number.

PHP version outputPHP 5.4.16 (cli) (built: Nov  6 2016 00:29:02)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies

Before we can move on, we have to modify the configuration file for PHP service slightly to make it use our unprivileged caddy user to run the server. The default configuration on CentOS assumes that Apache is the server of choice.

Open the PHP-FPM configuration file with vi or your favorite text editor. Here’s a short introduction to viif you’re not familiar with it.

sudo vi /etc/php-fpm.d/www.conf

Find the fragment that specifies the user account and group./etc/php-fpm.d/www.conf

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = apache
; RPM: Keep a group allowed to write in log dir.
group = apache

Change both values to caddy as follows:/etc/php-fpm.d/www.conf

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = caddy
; RPM: Keep a group allowed to write in log dir.
group = caddy

Save and close the file to exit. For Caddy to be able to communicate with PHP, start the PHP service.

sudo systemctl start php-fpm

All of WordPress’ dependencies are installed, so next, we’ll configure a MySQL database for WordPress to use.

Step 2 — Creating a MySQL Database and Dedicated User

WordPress uses a MySQL database to store all of its information. In a default MySQL installation, only a root administrative account is created. This account shouldn’t be be used because its unlimited privileges to the database server are a security risk. Here, we will create a dedicated MySQL user for WordPress to use and a database that the new user will be allowed to access.

First, log in to the MySQL root administrative account.

mysql -u root -p

You will be prompted for the password you set for the MySQL root account during installation.

Create a new database called wordpress which will be used for the WordPress website. You can use a different name, but make sure you remember it for additional configuration later.

CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Next, create a new user that will be allowed to access this database. Here, we use the username wordpressuser for simplicity, but you can choose your own name. Remember to replace password with a strong and secure password.

GRANT ALL ON wordpress.* TO 'wordpressuser'@'localhost' IDENTIFIED BY 'password';

Note: Bear in mind that the default password policy requires 12 characters, with at least one uppercase letter, one lowercase letter, one number and one special character. If you forget to follow that policy the above command will not create the user but show an error message instead.

Flush privileges to notify the MySQL server of the changes.

FLUSH PRIVILEGES;

You can now safely exit MySQL.

EXIT;

WordPress has a dedicated database and user account, so all the system components are set up. The next step is to install WordPress itself.

Step 3 — Downloading WordPress

Installing WordPress involves downloading the latest release into the web root directory and making sure it’s accessible by the web server, then finishing the installation via WordPress’ graphical interface. In this step, we’ll just download the release, because we’ll need to configure the web server before we can access the GUI.

First, change the current directory to /var/www, the web root which stores your website files.

cd /var/www

Download the latest compressed WordPress release. It’s important to use the latest release because the software is frequently updated with security patches.

sudo curl -O https://wordpress.org/latest.tar.gz

Extract the compressed archive you just downloaded.

sudo tar zxf latest.tar.gz

This will automatically create a new directory called wordpress. You can now safely remove the downloaded archive, as it’s no longer needed.

sudo rm latest.tar.gz

The last step is to change the permissions of WordPress files and directories so that all files are writable by Caddy. This will allow WordPress to be automatically updated to newer versions.

sudo chown -R caddy:caddy wordpress

Note: Choosing the right permissions for WordPress files is a matter of preference and administrative practices. Disallowing write access to WordPress files can increase security by making it impossible to exploit some bugs that could lead to compromising WordPress core files, but at the same time, it results in disabling automatic security updates and the ability to install and update plugins through the WordPress web interface. 

Next, you need to modify the web server’s configuration to serve your website.

Step 4 — Configuring Caddy to Serve the WordPress Website

Here, we will modify the Caddyfile configuration file to tell Caddy where our WordPress installation is located and under which domain name should it be published to the visitors.

Open the configuration file with vi or your favourite text editor

sudo vi /etc/caddy/Caddyfile

Copy and paste the following configuration into the file. You can remove any example configuration from previous tutorials./etc/caddy/Caddyfile

example.com {
    tls [email protected]
    root /var/www/wordpress
    gzip
    fastcgi / 127.0.0.1:9000 php
    rewrite {
        if {path} not_match ^\/wp-admin
        to {path} {path}/ /index.php?_url={uri}
    }
}

This Caddyfile is structured as follows:

  • The example.com in the first line is the domain name under which the site will be available. Replace it with your own domain name.
  • The [email protected] after the tls directive tells Caddy the e-mail address it should use to request the Let’s Encrypt certificate. If you’ll ever need to recover the certificate, Let’s Encrypt will use this e-mail address in the recovery process.
  • The root directive tells Caddy where the website files are located. In this example, it’s /var/www/wordpress.
  • The gzip directive tells Caddy to use Gzip compression to make the website faster.
  • The fastcgi directive configures the PHP handler to support files with a php extension
  • Using rewrite directive enables pretty URLs (called pretty permalinks in WordPress). This configuration is automatically provided by WordPress in the .htaccess file if you use Apache, but needs to be configured for Caddy separately.

After changing the configuration file accordingly, save the file and exit.

Restart Caddy to put the new configuration file settings into effect.

sudo systemctl restart caddy

When Caddy starts, it will automatically obtain an SSL certificate from Let’s Encrypt to serve your site securely using TLS encryption. You can now access your Caddy-hosted WordPress website by navigating to your domain using your web browser. When you do so, you will notice the green lock sign in the address bar meaning the site is being displayed over a secure connection.

You have now installed and configured Caddy and all necessary software to host a WordPress website. The last step is to finish WordPress’ configuration using its graphical interface.

Step 5 — Configuring WordPress

WordPress has a GUI installation wizard to finish its setup, including connecting to the database and setting up your first website.

When you visit your new WordPress instance in your browser for the first time, you’ll see a list of languages. Choose the language you would like to use. On the next screen, it describe the information it needs about your database. Click Let’s go!, and the next page will ask for database connection details. Fill in this form as follows:

  • Database Name should be wordpress, unless you customized it in Step 2.
  • Username should be wordpressuser, unless you customized it in Step 2.
  • Password should be the password you set for wordpressuser in Step 2.
  • Database Host and Table Prefix should be left to their default values.

When you click Submit, WordPress will check if the provided details are correct. If you receive an error message, double check that you entered your database details correctly.

Once WordPress successfully connects to your database, you’ll see a message which begins with All right, sparky! You’ve made it through this part of the installation. WordPress can now communicate with your database.

Now you can click Run the install to begin the installation. After a short time, WordPress will present you with a final screen asking for your website details, such as the website title, the administrator account username, password, and e-mail address. The strong password will be auto-generated for you, but you can choose your own if you’d like.

Note: It’s a good security practice not to use a common username like admin for the administrative account, as many security exploits rely on standard usernames and passwords. Choose a unique username and a strong password for your main account to help make your site secure.

After clicking Install WordPress, you will be directed to the WordPress dashboard. You have now finished the WordPress installation, and you can use WordPress freely to customize your website and write posts and pages.

Conclusion

You now have a working WordPress installation served using the Caddy web server. Caddy will automatically obtain SSL certificates from Let’s Encrypt, serve your site over a secure connection, and use HTTP/2 and Gzip compression to serve the website faster. You can read more about Caddy’s unique features and configuration directives for the Caddyfile in the official Caddy documentation.

If you want to use plugins with your new WordPress instance, note that some plugins rely on the Apache web server’s .htaccess files. Web servers other than Apache have become common with WordPress, so not many of these .htaccess-dependent plugins exist. However, the few that do exist won’t work out of the box with Caddy because it doesn’t use .htaccess. This is a good thing to keep in mind if you run into issues with WordPress plugins when using Caddy.

Most plugins that rely on .htaccess are caching plugins (for example, W3 Total Cache) which use .htaccess to circumvent PHP entirely for processing. Another example is Wordfence, which is a web application firewall module that uses .htaccess by default, but it properly supports different configuration models.

How To Host a Website with Caddy on CentOS 7

Introduction

Caddy is a new web server created with ease of use in mind. It’s simple enough to be used as a quick development server and robust enough to be used in production environments.

It features an intuitive configuration file, HTTP/2 support, and automatic TLS encryption. HTTP/2 is the new version of the HTTP protocol that makes websites faster by using single connection for transferring multiple files and header compression among other features. TLS is used to serve websites encrypted over a secure connection and, while it has been widely adopted on the Internet, it’s often a hassle to get and install certificates manually.

Caddy integrates closely with Let’s Encrypt, a certificate authority which provides free TLS/SSL certificates and automatically obtains and renews the certificates when needed. In other words, every website that Caddy serves can be automatically served over a secure connection with no additional configuration or action necessary.

In this tutorial, you will install and configure Caddy. After following this tutorial, you will have a simple working website served using HTTP/2 and a secure TLS connection.

Prerequisites

To follow this tutorial, you will need:

  • One CentOS 7 server set up with this initial server setup tutorial, including a sudo non-root user.
  • A domain name configured to point to your server. This is necessary for Caddy to obtain an SSL certificate for the website; without using a proper domain name, the website will not be served securely with TLS encryption. You can learn how to point domains to DigitalOcean Droplets by following the How To Set Up a Host Name with DigitalOcean tutorial.
  • Optionally, the nano text editor installed with sudo yum install nano. CentOS comes with the vitext editor by default, but nano can be more user friendly.

Step 1 — Installing the Caddy Binaries

The Caddy project provides an installation script that will retrieve and install the Caddy server’s binary files. To execute it, type:

curl -s https://getcaddy.com | bash

You can view the script by visiting https://getcaddy.com in your browser or downloading the file with wget or curl before you execute it.

During the installation, the script will use sudo to gain administrative privileges in order to put Caddy files in system-wide directories, so it might prompt you for a password.

The command output will look like this:

Caddy installation script outputDownloading Caddy for linux/amd64...
https://caddyserver.com/download/linux/amd64?plugins=
Extracting...
Putting caddy in /usr/local/bin (may require password)

[sudo]

password for sammy: Caddy 0.10.2 Successfully installed

After the script finishes, the Caddy binaries are installed on the server and ready to use. You can verify that Caddy binaries have been put in place by using which to check their location.

which caddy

The command output will say that the Caddy binary can be found in /usr/local/bin/caddy.

Caddy does not create any system-wide configuration during installation and does not install itself as a service, which means it won’t start up automatically during boot. In the next few steps, we’ll create the user account to use with Caddy, files Caddy needs to function and install its service file.

Step 2 — Creating the User and Group for Caddy

While Apache and Nginx, two most popular HTTP servers, create their own unprivileged users during installation from system packages, Caddy doesn’t do that. For security reasons it should not be started using the superuser root account either. In this step we will create a dedicaded user named caddy which will be solely used for running Caddy and accessing its files.

To create user named caddy let’s type:

sudo adduser -r -d /var/www -s /sbin/nologin caddy

The -r switch makes the newly created account a so called system account, the -d switch denotes the home directory for this user, in our case it will be /var/www which we will create later on. The unprivileged user should not be able to login and access system shell, which we make sure of with -s switch setting up a desired shell to /sbin/nologin, a system command disallowing system login. The last parameter is the username itself – in our case, caddy.

Now, when we have the user for Caddy web server available, we can configure necessary directories for storing Caddy configuration files in the next step.

Step 3 — Setting Up Necessary Directories

Caddy’s automatic TLS support and unit file (which we’ll install in the next step) expect particular directories and files to exist with specific permissions. We’ll create them all in this step.

First, create a directory that will house the main Caddyfile, which is a configuration file that tells Caddy what websites should it serve and how.

sudo mkdir /etc/caddy

Change the owner of this directory to the root user and its group to www-data so Caddy can read it.

sudo chown -R root:caddy /etc/caddy

In this directory, create an empty Caddyfile which we’ll edit later.

sudo touch /etc/caddy/Caddyfile

Create another directory in /etc/ssl. Caddy needs this to store the SSL private keys and certificates that it automatically obtains from Let’s Encrypt.

sudo mkdir /etc/ssl/caddy

Caddy needs to be able to write to this directory when it obtains the certificate, so make the owner the caddy user . You can leave the group as root, unchanged from the default:

sudo chown -R caddy:root /etc/ssl/caddy

Then make sure no one else can read those files by removing all the access rights for others.

sudo chmod 0770 /etc/ssl/caddy

The final directory we need to create is the one where the website itself will be published. We will use /var/www, which is customary and also the default path when using other web servers, like Apache or Nginx.

sudo mkdir /var/www

This directory should be completely owned by caddy.

sudo chown caddy:caddy /var/www

You have now prepared the necessary environment for Caddy to run. In the next step, we will configure Caddy as a system service to ensure it starts with system boot and can be managed with systemctl.

Step 4 — Installing Caddy as a System Service

While Caddy does not install itself as a service, the project provides an official systemd unit file. This file does assume the directory structure we set up in the previous step, so make sure your configuration matches.

Download the file from the official Caddy repository. The additional -o parameter to the curl command will save the file in the /etc/systemd/system/ directory and make it visible to systemd.

sudo curl -s https://raw.githubusercontent.com/mholt/caddy/master/dist/init/linux-systemd/caddy.service -o /etc/systemd/system/caddy.service

Before we can move on, we have to modify the file slightly to make it use our unprivileged caddy user to run the server.

Let’s open the file with vi or your favourite text editor (here’s a short introduction to vi)

sudo vi /etc/systemd/system/caddy.service

and find the fragment responsible for specifying the user account and group./etc/systemd/system/caddy.service

; User and group the process will run as.
User=www-data
Group=www-data

Change both values to caddy as follows:/etc/systemd/system/caddy.service

; User and group the process will run as.
User=caddy
Group=caddy

Save and close the file to exit. The service file is now ready to be used with our installation. Make systemdaware of the new service file.

sudo systemctl daemon-reload

Then, enable Caddy to run on boot.

sudo systemctl enable caddy.service

You can verify that the service has been properly loaded and enabled to start on boot by checking its status.

sudo systemctl status caddy.service

The output should look as follows:

Caddy service status output● caddy.service - Caddy HTTP/2 web server
   Loaded: loaded (/etc/systemd/system/caddy.service; enabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: https://caddyserver.com/docs

Specifically, it says that the service is loaded and enabled, but it is not yet running. We will not start the server just yet because the configuration is still incomplete.

You have now configured Caddy as a system service which will start automatically on boot without the need to run it manually. Next, we’ll allow web traffic through the firewall.

Step 5 — Allowing HTTP and HTTPS Connections (optional)

If you have followed Additional Recommended Steps for New CentOS 7 Servers tutorial as well and are using a firewall, we have to manually add firewall rules to pass through the internet traffic to Caddy.

Caddy serves websites using HTTP and HTTPS protocols, so we need to allow access to the appropriate ports in order to make Caddy available from the internet.

sudo firewall-cmd --permanent --zone=public --add-service=http 
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

All three commands, when run, will output the following success message:

firewall-cmd outputsuccess

This will allow Caddy to serve websites to the visitors freely. In the next step, we will create a sample web page and update the Caddyfile to serve it in order to test the Caddy installation.

Step 6 — Creating a Test Web Page and a Caddyfile

Let’s start by creating a very simple HTML page which will display a plain Hello World! message. This command will create an index.html file in the website directory we created earlier with just the one line of text, <h1>Hello World!</h1>, inside.

echo '<h1>Hello World!</h1>' | sudo tee /var/www/index.html

Next, we’ll fill out the Caddyfile. The Caddyfile, in its simplest form, consists of one or more server blockswhich each define the configuration for a single website. A server block starts with an address definition and is followed by curly braces. Inside the curly braces, you can include configuration directives to apply to that website.

An address definition is specified in the form protocol://host:port. Caddy will assume some defaults by itself if you leave some fields blank. For example, if you specify the protocol but not the port, the latter will be automatically derived (i.e. port 80 is assumed for HTTP, and port 443 is assumed for HTTPS). The rules governing the address format are described in-depth in the official Caddyfile documentation.

Open the Caddyfile you created in Step 2 using vi or your favorite text editor.

sudo vi /etc/caddy/Caddyfile

Paste in the following contents:/etc/caddy/Caddyfile

http:// {
    root /var/www
    gzip
}

Then save the file and exit. Let’s explain what this specific Caddyfile does.

Here, we’re using http:// for the address definition. This tells Caddy it should bind to port 80 and serve all requests using plain HTTP protocol (without TLS encryption), regardless of the domain name used to connect to the server. This will allow you to access the websites Caddy is hosting using your server’s IP address.

Inside the curly braces of our server block, there are two directives:

  • The root directive tells Caddy where the website files are located. In our example, it’s /var/www, where we created the test page.
  • The gzip directive tells Caddy to use Gzip compression to make the website faster. It does not need additional configuration.

Once the configuration file is ready, start the Caddy service.

sudo systemctl start caddy

We can now test if the website works. For this you use your server’s public IP address. If you do not know your server’s IP address, you can get it with curl -4 icanhazip.com. Once you have it, visit http://your_server_ip in your favorite browser to see the Hello World! website.

This means your Caddy installation is working correctly. In the next step, you will enable a secure connection to your website with Caddy’s automatic TLS support.

Step 7 — Configuring Automatic TLS

One of the main features that distinguishes Caddy from other web servers is its ability to automatically request and renew TLS certificates from Let’s Encrypt, a free certificate authority (CA). In addition, setting Caddy up to automatically serve websites over secure connection only requires a one line change in the Caddyfile.

Caddy takes care of enabling secure HTTPS connection for all configured server blocks and obtaining necessary certificates automatically, assuming some requirements are met by the server blocks configuration.

In order for TLS to work, the following requirements must be met:

  • Caddy must be able to bind itself to port 443 for HTTPS, and the same port must be accessible from the internet.
  • The protocol must not be set to HTTP, the port must not be not set to 80, and TLS must not be explicitly turned off or overridden with other settings (e.g. with the tls directive in the server block).
  • The hostname must be valid domain name; it must not not empty or set to localhost or an IP address. This is necessary because Let’s Encrypt can only issue certificates to valid domain names.
  • Caddy must know the email address that can be used for key recovery with Let’s Encrypt.

If you’ve been following this tutorial, the first requirement is already met. However, the current server block address is configured simply as http://, defining a plain HTTP scheme with no encryption as well as no domain name. We have also not provided Caddy with an e-mail address which Let’s Encrypt requires when requesting for a certificate. If the address is not supplied in the configuration, Caddy asks for it during startup. However, because Caddy is installed as a system service, it cannot ask questions during startup and in the result it will not start properly at all.

To fix this, open the Caddyfile for editing again.

sudo vi /etc/caddy/Caddyfile

First, replace the address definition of http:// with your domain. This removes the insecure connection forced by HTTP and provides a domain name for the TLS certificate. Second, provide Caddy with an email address using the tls directive inside the server block.

The modified Caddyfile should look as follows, with your domain and email address substituted in:/etc/caddy/Caddyfile

example.com {
    root /var/www
    gzip
    tls [email protected]
}

Save the file and exit the editor. To apply the changes, restart Caddy.

sudo systemctl restart caddy

Now direct your browser to https://example.com to verify if the changes were applied correctly. If so, you should once again see the Hello World! page. This time you can check that the website is served with HTTPS by looking at the URL or for a lock symbol in the URL bar.

Conclusion

You have now configured Caddy to properly serve your website over a secure TLS connection. It will automatically obtain and renew certificates from Let’s Encrypt, serve your site over a secure connection using the newer HTTP/2 protocol, and reduce loading time by using gzip compression.

This is a simple example to get started with Caddy. You can read more about Caddy’s unique features and configuration directives for the Caddyfile in the official Caddy documentation.