Skip to content

Restrict access to upload folders (.htaccess)

RussH edited this page May 6, 2021 · 25 revisions

To restrict accessing / executing php or other scripts from uploads or other restricted folders, use this code in .htaccess file put in that upload folder. If possible please have ownership of this .htaccess file as root and not your web server to prevent overwriting.

This is syntax for an Apache webserver.

1. Ownership

Ensure your upload directories are owned by whatever process runs your web server (usually www-data or apache) - and ensure permissions are set to 766 - 755 if this causes problems, and never 777!
(I would prefer 666 but this seems to break the app)

chown apache:apache -R uploads/
chmod 766 -R uploads/

I would set htaccess to be r/w by owner (root) and read by group/world

chmod 644 .htaccess

2 .htaccess

Generally, htaccess is owned by the web process (www-data or apache) however in this instance as opencats will not rewrite it, it's more secure if .htaccess is owned and writable by root only.

for Apache 2.2

# Don't list directory contents
IndexIgnore *
# Disable script execution
AddHandler cgi-script .php .php2 .php3 .php4 .php5 .php6 .php7 .php8 .php9 .pl .py .js .jsp .asp .htm .html .shtml .sh .cgi

Options -ExecCGI -Indexes

# Only the following file extensions are allowed (pdf, rtf, odt, doc, docx, txt, wpd)
Order Allow,Deny
Deny from all

<FilesMatch "\.([Pp][Dd][Ff]|[Dd][Oo][Cc][Xx]?|[Rr][Tt][Ff]|[Oo][Dd][Tt]|[Tt][Xx][Tt]|[Ww][Pp][Dd])$">

Allow from all
</FilesMatch>

# Block double extensions from being uploaded or accessed
<FilesMatch ".*\.([^.]+)\.([a-zA-Z0-9]+)$">
Order Deny,Allow
Deny from all
</FilesMatch>

On Apache 2.4 the syntax changes - therefore

*untested as yet - anyone able to confirm?

IndexIgnore *
# Disable script execution
AddHandler cgi-script .php .php2 .php3 .php4 .php5 .php6 .php7 .php8 .php9 .pl .py .js .jsp .asp .htm .html .$

Options -ExecCGI -Indexes
<FilesMatch "\.([Pp][Dd][Ff]|[Dd][Oo][Cc][Xx]?|[Rr][Tt][Ff]|[Oo][Dd][Ff]|[Tt][Xx][Tt]|[Ww][Pp][Dd])$">
Require all granted
</FilesMatch>
<FilesMatch ".*\.([^.]+)\.([a-zA-Z0-9]+)$">
Require all denied
</FilesMatch>

Finally of course - test, test, test.. once you add your htaccess file, please try to upload valid and invalid files.

Clone this wiki locally