Getting Started With Auto Secure Caddy Server

Hi there, you will read how caddy platform able power up your sites more secure, scalable, easy to manage and reliable.

Have you ever feel frustrated when configuring your web server with Apache & Nginx with attach ssl encryption and complex config on each site. Caddy is here to help you simply serve your sites secure, reliable and scalable. [Official Website]

Most implementation using caddy is reverse proxy. Let say for your docker app, go app, next-app, nodejs app and others app, but actually caddy server is server of servers. Caddy is written with Go.

Sample Use Case

Let say you have next.js or expres.js app that running on port 3000. This is the way how you can config on your web server (caddy).

Find Caddy File

sudo nano /etc/caddy/Caddyfile

Edit CaddyFile like sample below

api.mysaasapp.ai {
    reverse_proxy localhost:3000

    # Security headers
    header {
        Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
        X-Content-Type-Options "nosniff"
        X-Frame-Options "DENY"
    }

    # Optional: CORS (if needed for frontend)
    @cors header Origin *
    @cors header @cors Origin https://app.mysaasapp.ai
    respond @cors 200 {
        headers {
            Access-Control-Allow-Origin "https://app.mysaasapp.ai"
            Access-Control-Allow-Methods "GET, POST, OPTIONS"
            Access-Control-Allow-Headers "Content-Type, Authorization"
        }
    }
}

If you have multiple domain and application in your hosted server, It’s no problem in caddy. You only write like this :

example.com {
    root * /var/www/html
    file_server
}

api.example.com {
    reverse_proxy localhost:3000
}

admin.example.com {
    reverse_proxy localhost:5000
}

If your app in Php such as WordPress, Laravel, CI or others, you may follow this configuration on CaddyFile.

// Some code
mywebsite.com {
 root * /var/www/wordpress
 encode
 php_fastcgi unix//run/php8.1/php-version-fpm.sock
 file_server
}

No need to install ssl manually, It’s automatically attached by Caddy.

How to Setup Load Balance with Caddy

You just define the instance and setup Load Balance method. This example below using round-robin method with optional Health Checks, retries. Let’s take an example you have 3 instance running on your server :

localhost:3000, localhost: 3001 and localhost:5000

Open and update your caddy file and you may follow like this config example

api.myapp.ai {
    reverse_proxy {
        to localhost:3000 localhost:3001 localhost:5000
        lb_policy round_robin
        health_uri /health-check
        health_interval 10s
        health_timeout 3s
    }
}

What do you think with Caddy? It’s more simple right.