How to Install Caddy on Fedora 40/39/38 Linux

This guide will demonstrate how to install Caddy on Fedora Linux, presenting two distinct methods: the use of Fedora’s default appstream and the alternative approach employing caddy copr via the command-line terminal.

Caddy, known for its simplicity and efficiency, stands out as an innovative solution in the realm of web servers. Its ease of use, combined with robust features, makes it a preferred choice for developers and system administrators. In this guide, we’ll explore the installation process on Fedora Linux, a popular choice for its cutting-edge technology and stability.

Here’s what makes Caddy noteworthy:

  • Automatic HTTPS: Caddy simplifies the process of securing websites with HTTPS, automatically obtaining and renewing SSL/TLS certificates.
  • Speed and Performance: Built with modern standards in mind, it ensures fast and reliable performance.
  • Extensibility: Its modular architecture allows for extensions, offering flexibility to meet diverse needs.
  • Ease of Configuration: Caddy’s human-readable configuration files make setup and maintenance straightforward.
  • Cross-Platform Compatibility: It runs smoothly across various operating systems, ensuring a wide range of applicability.

As we delve into the installation process, we’ll navigate through the simplicity of Caddy, leveraging its features to enhance your web-serving experience. The guide will provide clear, step-by-step instructions, ensuring a smooth and successful installation on your Fedora system.

Install Caddy with Fedora Appstream

Initiating Installation

Begin by installing Caddy directly from Fedora’s repository. Execute this command in your terminal to start the installation process:

sudo dnf install caddy

This command utilizes sudo for administrative privileges and dnf, Fedora’s package manager, to fetch and install Caddy.

Screenshot of Caddy installation process in Fedora Appstream
Step-by-step process of installing Caddy via Fedora Appstream

Verifying the Installation

Post-installation, it’s crucial to verify that Caddy is correctly installed. Use the command below to check the installed version of Caddy:

caddy version

This command displays the version of Caddy currently installed on your system. It’s a straightforward way to ensure the installation was successful.

Choosing the Right Version

The version installed from Fedora’s repository suffices for most users and system administrators. It offers stability and compatibility with your Fedora system. However, if you require the latest version of Caddy with recent updates and features, consider the next section for an alternative installation method. This approach is particularly beneficial for those who need the most up-to-date features and improvements.

Install Caddy with COPR @caddy/caddy on Fedora

Enabling Caddy COPR Repository

To install the latest version of Caddy on your Fedora system, first enable the @caddy/caddy COPR repository. COPR repositories in Fedora provide additional packages that are not available in the default repositories.

Run this command in your terminal:

sudo dnf copr enable @caddy/caddy

Using sudo grants necessary permissions, while dnf copr enable activates the specified repository, in this case, @caddy/caddy, which hosts the latest version of Caddy.

Enabling Caddy-Copr repository on Fedora Linux
Screenshot showing how to enable the Caddy-Copr repository

Installing or Upgrading Caddy from COPR Repository

With the repository enabled, proceed to install Caddy. Execute the following command:

sudo dnf install caddy

This command follows the standard installation procedure, similar to installing from Fedora’s default repository, but fetches Caddy from the newly enabled COPR repository, ensuring you receive the most current version.

Installation prompt for Caddy from Caddy-Copr on Fedora
Prompt for installing Caddy from the Caddy-Copr repository

Verifying the Installation

After installation, it’s important to verify that the latest version of Caddy is successfully installed. To do this, use:

caddy version

This command displays the version details of Caddy installed on your system. It confirms that you have the up-to-date version, aligning with the requirements of advanced users or those needing the latest features.

Verify Caddy Service on Fedora

Checking Caddy Service Status

First, enable Caddy with the following command:

sudo systemctl enable caddy --now

To confirm that the Caddy Web Server service is running correctly, use the following command:

systemctl status caddy

This command, executed with systemctl, a system and service manager in Linux, provides the current status of the Caddy service. It will display whether the service is active, inactive, or facing any issues, offering an immediate understanding of Caddy’s operational state on your system.

Caddy web server systemd service status on Fedora Linux
Checking the systemd service status of Caddy on Fedora

Lastly, visit your domain or server IP address to confirm the installation and test page of Caddy:

Caddy test page display on Fedora Linux
Screenshot of the Caddy test page

If you cannot access the test page, the CaddyFile configuration may be incorrect. By default, port 80 and fileserver should be enabled on fresh installations to test the success of the installation. Later in the guide, we will cover the configurations of CaddyFile.

Additional Caddy Service Commands

Starting the Caddy Service

To start the Caddy service, particularly after installation or if it’s not running, use:

sudo systemctl start caddy

This command triggers the service to begin operation, ensuring that Caddy is active and ready to serve web content.

Enabling Caddy Service on Boot

To ensure Caddy starts automatically with your system boot, execute:

sudo systemctl enable caddy

This step is crucial for maintaining uninterrupted web server functionality, particularly for servers that require constant uptime.

Stopping the Caddy Service

If you need to stop the Caddy service for any reason, such as maintenance or troubleshooting, use:

sudo systemctl stop caddy

This command safely stops the Caddy service without disrupting the overall system functionality.

Restarting the Caddy Service

For applying configuration changes or after troubleshooting, restart the Caddy service with:

sudo systemctl restart caddy

Restarting is often necessary after configuration changes to ensure that Caddy operates with the latest settings.

Configure Firewalld for Caddy on Fedora

Firewalld is a dynamic firewall manager in Fedora that supports network/firewall zones to define the trust level of network connections or interfaces. Properly configuring Firewalld is crucial for ensuring that your Caddy server can communicate securely with the internet or other networks.

Basic Firewalld Configuration for Caddy

Allowing HTTP and HTTPS Traffic

By default, web servers use HTTP (port 80) and HTTPS (port 443). To allow traffic on these ports:

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

This set of commands adds HTTP and HTTPS services to the firewall rules and reloads Firewalld to apply the changes.

Verifying Allowed Services

To confirm the services are allowed:

sudo firewall-cmd --list-all

This command lists all current settings, including allowed services.

Advanced Firewalld Configuration for Custom Ports

Allowing Custom Ports

If Caddy is configured to use non-standard ports, you need to allow them through Firewalld. For example, to allow port 8080:

sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

Replace 8080 with your custom port number. The /tcp suffix specifies the TCP protocol.

Removing a Port or Service

To remove a port or service from the allowed list, use:

sudo firewall-cmd --permanent --remove-service=http
sudo firewall-cmd --permanent --remove-port=8080/tcp
sudo firewall-cmd --reload

Configuring Firewalld for Specific Zones

Adding Services to a Zone

Firewalld uses zones to apply different rules based on the network’s trust level. To add HTTP/HTTPS services to a specific zone, such as the public zone:

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

Listing Active Zones

To list all active zones and their settings:

sudo firewall-cmd --list-all-zones

This command helps you understand the current firewall configuration across different zones.

Changing the Default Zone

To change the default zone for an interface, such as eth0:

sudo firewall-cmd --permanent --zone=public --change-interface=eth0
sudo firewall-cmd --reload

This assigns the eth0 interface to the public zone.

IP Addresses Firewalld Configuration for Caddy on Fedora

Continuing with the configuration of Firewalld, we can also set up rules based on specific IP addresses or IP ranges, enhancing the security and control over who can access the Caddy server.

Allowing Traffic from a Specific IP Address

To allow traffic from a specific IP address, for instance, 192.168.1.100, on port 80 (HTTP):

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" port port=80 protocol=tcp accept'
sudo firewall-cmd --reload

This command creates a rich rule that specifically allows access on port 80 for the given IP address.

Allowing Traffic from a Subnet

For allowing an entire subnet, such as 192.168.1.0/24, you can use a similar approach:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port port=80 protocol=tcp accept'
sudo firewall-cmd --reload

This rule permits access to the server from any IP address within the specified subnet on port 80.

Blocking Traffic from a Specific IP Address

To block traffic from a particular IP address:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" reject'
sudo firewall-cmd --reload

This rule will prevent all incoming connections from the specified IP address.

Limiting Access to Specific Services

If you want to restrict access to the Caddy server based on IP addresses for specific services like HTTPS:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="https" accept'
sudo firewall-cmd --reload

This command allows access to HTTPS service only for the specified IP address.

Configuring Firewalld with IPv6 Addresses

Firewalld can also be configured for IPv6 addresses. For instance, to allow HTTP traffic from an IPv6 address:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv6" source address="2001:db8::1" port port=80 protocol=tcp accept'
sudo firewall-cmd --reload

This command configures Firewalld to accept HTTP traffic from the specified IPv6 address.

Enable PHP Support in Caddy on Fedora

Installing PHP

Initiate PHP support in Caddy by installing PHP on your Fedora system. Execute the following command:

sudo dnf install php php-fpm

This command will install PHP and PHP-FPM (FastCGI Process Manager). PHP-FPM is crucial for processing PHP files and is known for efficiently managing high-load scenarios, making it a suitable choice for web servers like Caddy.

Creating a Caddy Virtual Host Configuration File for PHP Testing

Once PHP is installed, proceed to set up a virtual host in Caddy for PHP file handling. Start by creating a new configuration file using a text editor such as nano:

sudo nano /etc/caddy/Caddyfile

In the file, input or modify the configuration as shown below:

http://your_domain_or_IP {
    root * /var/www/html
    php_fastcgi localhost:9000
    file_server
}

This configuration instructs Caddy to handle PHP requests with PHP-FPM, typically on port 9000, and to serve static files from the specified root directory. Ensure to replace your_domain_or_IP with your actual domain or IP address. This setup is essential for testing and validating PHP support in your Caddy server environment.

Configure PHP-FPM for Caddy From Apache

PHP-FPM is usually configured for Apache by default. For Caddy, similar to Nginx, adjustments are necessary. Open the configuration file:

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

Modify the user=apache and group=apache lines to match Caddy:

user = cady
group = cady
Modifying PHP FPM configuration for Caddy on Fedora
Changing PHP FPM’s www configuration file for Caddy

Also, alter the listen.acl_users line:

listen.acl_users = apache,nginx,caddy

Save with CTRL+O and exit with CTRL+X.

Restart PHP-FPM to activate these changes:

sudo systemctl restart php-fpm

Verifying Caddy PHP Support

To confirm PHP’s integration with Caddy, create a test PHP file:

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

This command generates an info.php file in the document root containing the PHP information script. Restart the Caddy service to implement the new settings:

sudo systemctl restart caddy

To test, navigate to http://your_domain_or_IP/info.php in your browser. A successful configuration will display PHP details from your server.

Displaying PHP info test results on Caddy server
PHP info test results on Caddy in Fedora Linux

Create a Static Website with Caddy on Fedora

Creating Directory Structure

Begin by setting up the directory structure for your static website. This will host your HTML files. Execute the following commands to establish the required directories:

Note: change example.com to your domain name.

sudo mkdir -p /var/www/html/my-static-site/
sudo mkdir /var/log/caddy

Assign ownership of these directories to Caddy:

sudo chown -R caddy:caddy /var/www/html/my-static-site/
sudo chown caddy:caddy /var/log/caddy

These commands create a directory at /var/www/html/my-static-site/, a standard location for web files in Linux. The -p flag ensures the creation of the entire path if it doesn’t already exist.

Creating HTML Files

Next, create the HTML files for your static website. Begin with an index file:

echo "<html><body><h1>Welcome to My Static Site</h1></body></html>" | sudo tee /var/www/html/my-static-site/index.html

This command creates a basic HTML file named index.html in your site’s directory, serving as the default file for Caddy when accessing your website’s root.

Creating a Caddy Virtual Host Configuration File

To serve your static site, configure a virtual host in Caddy. Open the Caddy configuration file:

sudo nano /etc/caddy/Caddyfile

Insert the following configuration:

example.com {
    root * /var/www/html/my-static-site
    file_server
    encode gzip

    log {
        output file /var/log/caddy/example.access.log
    }

    @static {
        file
        path *.ico *.css *.js *.gif *.jpg *.jpeg *.png *.svg *.woff *.pdf *.webp
    }
    header @static Cache-Control max-age=5184000

    tls name@example.com
}

This configuration includes several directives:

  • encode gzip compresses files using Gzip, enhancing load times.
  • The log directive specifies logging details, outputting access logs to /var/log/caddy/example.access.log.
  • The @static named matcher and header directive set cache control for static assets, like images and CSS files.
  • tls handles SSL certificate generation and installation, with an option to specify an email for Let’s Encrypt notifications.

After editing, save and close the file CTRL+O and CTRL+X.

Validating and Formatting the Configuration

Before restarting Caddy, validate your configuration:

caddy validate --adapter caddyfile --config /etc/caddy/Caddyfile

The --adapter caddyfile option is necessary as the default validation checks JSON configurations. If a formatting warning appears, resolve it with:

caddy fmt --overwrite /etc/caddy/Caddyfile

This command reformats and overwrites the Caddyfile.

Restarting Caddy

Apply your changes by restarting Caddy:

sudo systemctl restart caddy

Restart the server whenever you alter the configuration.

Upon completion, access your site via a browser to see your static website live, confirming the successful configuration of Caddy.

Caddy test HTML page successfully loaded on Fedora
Caddy test HTML page showing ‘OK’ status

Configuring Multiple Sites in Caddy on Fedora

Setting Up Individual Site Blocks

For hosting multiple sites with Caddy, you can configure each site in its dedicated block within a single Caddyfile. Structure each site’s configuration in separate blocks as follows:

example1.com {
    root * /var/www/example1.com/html
    ...
}

example2.com {
    root * /var/www/example2.com/html
    ...
}

This approach works well for a small number of sites. However, managing a single Caddyfile can become challenging as the number of hosted sites increases.

Organizing Configurations into Separate Files

Consider dividing the configurations into separate files to streamline the management of multiple sites. Start by creating a new directory to store these files:

sudo mkdir /etc/caddy/caddyconf

Next, incorporate these configuration files into your main /etc/caddy/Caddyfile. At the beginning of the Caddyfile, add:

import caddyconf/*.conf

This directive instructs Caddy to import all .conf files from the caddyconf directory, enabling you to manage each site’s configuration in an individual file.

Creating Individual Configuration Files

The final step involves creating a unique configuration file for each site. In the /etc/caddy/caddyconf directory, create a .conf file for each website you intend to host. Each file should contain the specific configuration for its respective site.

Configure Caddy as a Reverse Proxy on Fedora

Configuring Caddy as a reverse proxy allows it to direct requests to other servers, acting as an intermediary. This setup is beneficial for load balancing, enhancing security, and managing traffic efficiently. Follow these steps to set up Caddy as a reverse proxy on Fedora:

Setting Up Reverse Proxy Configuration

Open the Caddy configuration file to define the reverse proxy settings. Use the command:

sudo nano /etc/caddy/Caddyfile

In the configuration file, specify the reverse proxy settings as follows:

http://your_domain_or_IP {
    reverse_proxy /path/* http://backend_server_IP:port
}

Replace your_domain_or_IP with your domain or IP address, /path/* with the desired path to be proxied, and http://backend_server_IP:port with the address and port of the backend server you’re proxying requests to. This configuration directs requests coming to your_domain_or_IP/path to the specified backend server.

Applying the Configuration

After setting up the reverse proxy configuration, save the changes and exit the editor. To apply the new configuration, restart the Caddy service:

sudo systemctl restart caddy

This command ensures that Caddy reloads with the updated settings, enabling the reverse proxy functionality.

Testing the Reverse Proxy Setup

To confirm that the reverse proxy is functioning correctly, access http://your_domain_or_IP/path in a web browser. If configured properly, this should route the request to the backend server, displaying its response.

Best Practices for Reverse Proxy Configuration

  • Security: Implement SSL/TLS encryption to secure data transmission through the proxy.
  • Load Balancing: If you have multiple backend servers, configure Caddy to distribute traffic evenly among them.
  • Logging: Enable logging in Caddy to monitor the proxy’s performance and troubleshoot any issues.
  • Maintenance: Regularly update both Caddy and your backend servers to maintain security and performance.

Caddy Global Options on Fedora

Setting Global Options in the Caddyfile

Global options in the Caddyfile apply universally across all sites hosted on the server. Placing these options at the top of the Caddyfile streamlines configuration by eliminating the need to repeat them in each server block.

For comprehensive details on all available options, refer to the Caddy documentation.

Commonly Used Global Options

Here are some frequently utilized global options for your Caddyfile:

{
    # TLS Options
    email name@example.com

    servers :443 {
        protocol {
            experimental_http3
        }
        max_header_size 5mb
    }
    
    servers :80 {
        protocol {
            allow_h2c
        }
        max_header_size 5mb
    }
}

Understanding the Options

  • email: This is used to register the SSL certificate with Let’s Encrypt. Providing an email address is crucial for receiving important notifications regarding your SSL certificate.
  • servers :443 and servers :80: These specify configurations for HTTPS (:443) and HTTP (:80) servers, respectively.
  • protocol { experimental_http3 }: This enables the experimental HTTP/3 protocol for HTTPS sites. HTTP/3 is the upcoming version of the HTTP protocol, offering improved performance and security.
  • protocol { allow_h2c }: This enables HTTP/2 support for HTTP sites. HTTP/2 offers enhanced speed and efficiency over the older HTTP/1.1.
  • max_header_size: This option sets the maximum size of HTTP request headers that the server will parse. Here, it’s set to 5 MB, accommodating larger header sizes.

Important Considerations

While configuring global options, it’s crucial to consider the following:

  • Experimental Features: The use of experimental features, like HTTP/3, should be approached with caution. These features might undergo changes or be removed in future updates.
  • Security and Performance: Options like OCSP stapling and max_header_size impact both the security and performance of your websites. It’s essential to balance these aspects according to your specific needs.

Configure Caddy Security on Fedora

Enabling HTTP Authentication

Creating Authentication Credentials

To secure specific directories with HTTP authentication, start by generating authentication credentials. Caddy requires the use of hashed passwords. Generate a hashed password with:

caddy hash-password

Upon prompt, enter and confirm your password. The output will be a hashed password, for instance:

VRFTFJhgETzVdZWDwMhi3NkD0VQZkDJZ3ZlmEJEwjECE1z3aEOtWZ3Z5FYSVeBEa2EXV9tZ5hJcMJdNi

Configuring Caddyfile

Next, incorporate these credentials into your Caddyfile:

basicauth /hidden/* {
    Joshua
VRFTFJhgETzVdZWDwMhi3NkD0VQZkDJZ3ZlmEJEwjECE1z3aEOtWZ3Z5FYSVeBEa2EXV9tZ5hJcMJdNi
}

This configuration secures the /hidden directory with the specified credentials.

Hardening Site Security and Enabling HSTS

Creating a Security Configuration File

For enhanced security measures, create a dedicated configuration file:

sudo nano /etc/caddy/caddy_security.conf

Add the following security directives:

header {
    Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
    X-Xss-Protection "1; mode=block"
    X-Content-Type-Options "nosniff"
    X-Frame-Options "DENY"
    Permissions-Policy "interest-cohort=()"
    Content-Security-Policy "upgrade-insecure-requests"
    Referrer-Policy "strict-origin-when-cross-origin"
    Cache-Control "public, max-age=15, must-revalidate"
    Feature-Policy "accelerometer 'none'; ambient-light-sensor 'none'; autoplay 'self'; camera 'none'; encrypted-media 'none'; fullscreen 'self'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; midi 'none'; payment 'none'; picture-in-picture *; speaker 'none'; sync-xhr 'none'; usb 'none'; vr 'none'"
}

This code enhances site security by:

  • Enabling HSTS for the site and its subdomains.
  • Activating XSS filtering.
  • Blocking MIME type sniffing.
  • Prohibiting the site from being displayed in iframes.
  • Excluding the site from FLoC tracking trials.
  • Setting strict rules for handling insecure URLs.
  • Implementing a secure referrer policy.
  • Controlling browser features through the Feature Policy.

Importing Security Configuration in Site Blocks

To apply these settings, import the security file into the desired site blocks in your Caddyfile:

example.com {
    ...
    import /etc/caddy/caddy_security.conf
}

Restarting Caddy Server

Finally, restart the Caddy server to apply these security enhancements:

sudo systemctl restart caddy

This restart is necessary for Caddy to recognize and implement the new security configurations.

SELinux Configuration for Caddy: Potential Problems and Fixes on Fedora

SELinux (Security-Enhanced Linux) is an important security feature in Fedora, but it can sometimes interfere with web server operations, like those of Caddy. Understanding and resolving SELinux-related issues is crucial for a smooth running server.

Identifying SELinux Issues

SELinux operates in the background, enforcing security policies that might restrict Caddy’s operations. Common indicators of SELinux problems include:

  • Inaccessible web pages despite correct server configuration.
  • Log files indicating ‘Permission Denied’ errors.
  • Unexpected behavior not resolved by traditional troubleshooting.

Diagnosing SELinux Status

To determine SELinux’s operational status, use the command:

sestatus

This will display whether SELinux is enabled and its current mode – Enforcing, Permissive, or Disabled.

Adjusting SELinux Policies for Caddy

If SELinux is blocking Caddy, adjust policies rather than disabling SELinux entirely. Use the audit2allow utility to analyze log files and identify necessary policy changes. For example:

Check recent audit logs:

sudo grep caddy /var/log/audit/audit.log

Generate a custom policy module:

sudo grep caddy /var/log/audit/audit.log | audit2allow -M caddy

Apply the new policy:

sudo semodule -i caddy.pp

Setting Correct File Contexts

SELinux requires files and directories to have the correct security context. To update the context for Caddy’s web directory:

sudo restorecon -Rv /var/www/example.com/html

This command recursively applies the appropriate SELinux context to files in the specified directory.

Enabling HTTP Traffic in SELinux

Sometimes, SELinux may block HTTP traffic. To enable it:

sudo setsebool -P httpd_can_network_connect 1

This command allows web services like Caddy to establish network connections.

Resolving SELinux-related issues is a balance between maintaining security and ensuring functionality. Adjust SELinux policies and contexts as needed, but avoid disabling SELinux entirely, as it plays a vital role in system security if you are in a highly sensitive, risky environment.

Conclusion

Throughout this guide, we’ve walked through the essentials of setting up and configuring Caddy Web Server on Fedora, from a straightforward installation to enabling PHP support and even setting it up as a reverse proxy. Remember, the beauty of Caddy lies in its simplicity and versatility, so don’t hesitate to explore further customization to suit your specific needs. Keep your Caddy server updated and secure, and always back up your configurations.

Leave a Comment