Prevent some php_fastcgi paths from executing scripts

1. The problem I’m having:

I’m trying to prevent PHP script execution on given paths. For example path /upload/, which contains user uploaded data, must not execute any downloaded scripts and serve it as plain text.
How I can reach that?

2. Error messages and/or full log output:

3. Caddy version:

v2.8.4

4. How I installed and ran Caddy:

a. System environment:

Debian GNU/Linux 12.7 package. Systemd service

b. Command:

systemctl start caddy.service

c. Service/unit/compose file:

# caddy.service
#
# For using Caddy with a config file.
#
# Make sure the ExecStart and ExecReload commands are correct
# for your installation.
#
# See https://caddyserver.com/docs/install for instructions.
#
# WARNING: This service does not use the --resume flag, so if you
# use the API to make changes, they will be overwritten by the
# Caddyfile next time the service is restarted. If you intend to
# use Caddy's API to configure it, add the --resume flag to the
# `caddy run` command or use the caddy-api.service file instead.

[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network.target network-online.target
Requires=network-online.target

[Service]
Type=notify
User=caddy
Group=caddy
ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile
ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force
TimeoutStopSec=5s
LimitNOFILE=1048576
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target

d. My complete Caddy config:

domain.tld {
	root * /var/www/domain.tld

	encode {
		zstd better
		gzip 8
	}

	php_fastcgi unix//run/php/fpm.sock {
		try_files {path} {path}/index.php /routing.php =404

		@4xx status 400 403 405 408
		@5xx status 500 501 502 504 505 506 507 508

		handle_response @4xx {
			templates
			rewrite * /4xx.html
			file_server {
				status {rp.status_code}
			}
		}

		handle_response @5xx {
			templates
			rewrite * /5xx.html
			file_server {
				status {rp.status_code}
			}
		}
	}

	file_server {
		hide .git .git* package.json composer.lock composer.json .htaccess
	}
}

5. Links to relevant resources:

So, it’s simple. Just need to handle path with file_server.

@denyPhp {
	path /upload/* 
}

handle @denyPhp {
	file_server {
		hide *\.ph*
	}
}
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.