How to Prevent Cross-site scripting (XSS) attacks with .htaccess?
Cross-site scripting (XSS) is a type of web application vulnerability that can be exploited by attackers to inject malicious scripts into web pages viewed by other users. One way to prevent XSS attacks is by using .htaccess, a configuration file used by Apache web servers.
Here are some ways to prevent XSS through .htaccess:
- Set the Content Security Policy (CSP) header: The CSP header allows you to define a policy that restricts the types of content that can be loaded on your website. By setting the CSP header, you can prevent XSS attacks by disallowing the execution of any external scripts or stylesheets. You can add the following line to your .htaccess file to set the CSP header:
Header set Content-Security-Policy "default-src 'self'; script-src 'self'"
Header set Content-Security-Policy "default-src 'self'; script-src 'self'"
This line sets the default source to 'self' and only allows scripts from the same domain ('self').
- Enable mod_security: Mod_security is an Apache module that provides additional security features for web applications. It can help prevent XSS attacks by blocking requests that contain malicious code. You can enable mod_security by adding the following line to your .htaccess file:
SecFilterEngine On
SecFilterScanPOST On
This line turns on mod_security and enables it to scan POST requests for potential XSS attacks.
- Disable the use of certain HTML tags: Another way to prevent XSS attacks is by disabling the use of certain HTML tags that can be used to inject malicious code. You can add the following lines to your .htaccess file to disable the use of the script, iframe, and object tags:
<ifmodule mod_headers.c="">
Header set X-XSS-Protection "1; mode=block"
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
Header append Vary User-Agent env=!dont-vary
Header unset X-Powered-By
Header always append X-Frame-Options SAMEORIGIN
<filesmatch>
Order Allow,Deny
Deny from all
</filesmatch>
<ifmodule mod_php5.c="">
php_flag session.cookie_httponly on
</ifmodule>
<ifmodule mod_rewrite.c="">
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]
</ifmodule>
</ifmodule>
These lines also add some additional security measures like setting the X-XSS-Protection header, removing server information from headers, setting the X-Frame-Options header, and denying access to sensitive files.