It’s important to block unnecessary script execution on your website to deny attackers an opportunity to exploit your website. .htaccess file allows you to do that without accessing Apache server configuration. Here’s how to deny script execution using .htaccess.
How to Deny Script Execution using .htaccess
Here are the steps to deny script execution using .htaccess. Before proceeding further, please ensure that you have enabled .htaccess (mod_rewrite) in your Apache web server. Here’s how to do it :
1. Open .htaccess file
Open .htaccess file in a text editor. You will typically find it at your website root (/var/www/html)
$ sudo vim /var/www/html/.htaccess
2. Deny Script Execution
Generally, attackers upload script files (php, js) to your website folder (e.g /public/products/upload), where they are processed automatically and run, causing unexpected consequences. So we will block php and other script-based files from being uploaded to your folder. Just add the following lines to your .htaccess file
<Directory "^html/product/uploads"> <Files "^(*.php|*.js|*.pl|*.py|*.jsp|*.asp)"> order deny,allow deny from all </Files> </Directory>
You can also add the following line to ensure that whenever someone requests a script file, it is served as plain text
<FilesMatch "\.(php|pl|py|jsp|asp|htm|shtml|sh|cgi)$"> ForceType text/plain </FilesMatch>
3. Restart Apache web server
Restart Apache web server to apply changes
$ sudo /etc/init.d/apache2 start [Debian or Ubuntu] # sudo apachectl restart [RHEL, CentOS or Fedora]
That’s it! This will prevent malicious scripts from being uploaded as well as script-based files being requested unnecessarily.