این راهنما یک پیکربندی جامع برای فایل .htaccess سرورهای آپاچی ارائه میدهد که بر روی **تقویت امنیت**، **بهینهسازی عملکرد** و انطباق با بهترین شیوههای OWASP تمرکز دارد. کد زیر یک فایل .htaccess کامل و آماده استفاده است. همیشه قبل از پیادهسازی بر روی سرور اصلی، آن را در یک محیط آزمایشی (Staging) بررسی کنید.
.htaccess میتواند عملکرد سایت را تحت تأثیر قرار دهد. قبل از هرگونه تغییر، از فایلهای خود نسخه پشتیبان تهیه کنید و به دقت آن را تست کنید. این پیکربندی فرض را بر این میگذارد که از آپاچی نسخه 2.4+ استفاده میکنید و ماژولهای رایجی مانند `mod_rewrite` و `mod_headers` فعال هستند.
فایل .htaccess امکان پیکربندی سطح دایرکتوری را برای سرورهای وب آپاچی فراهم میکند، بدون نیاز به ویرایش فایل اصلی پیکربندی سرور. این فایل معمولاً برای بازنویسی URL، کنترل دسترسی، هدرهای امنیتی، کشینگ و فشردهسازی استفاده میشود. این راهنما یک تنظیمات کامل برای محافظت در برابر تهدیدات رایج مانند XSS، SQL Injection و حملات DoS را پوشش میدهد، ضمن اینکه سرعت سایت را نیز بهبود میبخشد.
کد زیر را کپی کرده و در فایل .htaccess در پوشه اصلی وبسایت خود قرار دهید.
# Complete .htaccess configuration for enhanced security, performance, and OWASP compliance
# This file includes mod_rewrite for URL security, headers for protection, expires for caching,
# deflate for compression, and general server hardening settings.
# Enable mod_rewrite for URL rewriting, security rules, and redirects
<IfModule mod_rewrite.c>
# Turn on the rewrite engine
RewriteEngine On
# Block common XSS attempts in query strings (e.g., <script> tags and related)
RewriteCond %{QUERY_STRING} (^|&)(<|&%3C).*script.*(>|&%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (^|&)(<|&%3C).*iframe.*(>|&%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (^|&)(<|&%3C).*object.*(>|&%3E) [NC,OR]
RewriteCond %{QUERY_STRING} (^|&)(<|&%3C).*embed.*(>|&%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _GET(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _POST(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _COOKIE(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _SESSION(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Redirect suspicious XSS queries to warning page with parameters
RewriteRule ^(.*)$ https://www.miralishahidi.ir/warning.php?blocked=xss [R=301,L,QSA,E=blocked:xss]
# Block SQL Injection patterns in query strings (based on OWASP guidelines)
RewriteCond %{QUERY_STRING} (union\\s+(all\\s+)?select|select\\s+.*\\s+from|insert\\s+into|drop\\s+(table|database|schema)|update\\s+.*\\s+set|delete\\s+from|create\\s+(table|database|view|index)|alter\\s+(table|database)|exec|execute|sp_|\\b(and|or)\\b(\\s+.*)?(=|>|<|like|between|--|\\/\\*|\\*\\/|;|#)) [NC,OR]
RewriteCond %{QUERY_STRING} ('|")(\\s+.*)?(\\s+.*)?(or|and)(\\s+.*)?(=|>|<) [NC,OR]
RewriteCond %{QUERY_STRING} (\\.{2}\\/|%2e%2e\\/|%252e%252e%2f|~|etc\\/passwd|\\/etc\\/hosts|boot\\.ini|win\\.ini) [NC,OR]
# Redirect SQL injection attempts to warning page
RewriteRule ^(.*)$ https://www.miralishahidi.ir/warning.php?blocked=sql [R=301,L,QSA,E=blocked:sql]
# Block Directory Traversal attempts (e.g., ../ paths and system file access)
RewriteCond %{QUERY_STRING} (\\.{2}\\/|%2e%2e\\/|%252e%252e%2f|~|etc\\/passwd|\\/etc\\/hosts|boot\\.ini|win\\.ini|\\/proc|\\/sys|\\/dev|\\/tmp) [NC,OR]
RewriteCond %{REQUEST_URI} (\\.{2}\\/|%2e%2e\\/|~) [NC]
# Block traversal and return 403 Forbidden
RewriteRule ^(.*)$ - [F,L,E=blocked:traversal]
# Block Command Injection patterns (shell commands, system calls, etc.)
RewriteCond %{QUERY_STRING} (\\;|&&|\\|\\||\\/bin\\/|\\/usr\\/|\\/etc\\/|cmd\\.exe|\\/s?bin\\/|powershell|whoami|id|cat|ls|dir|ping|netstat|ps|top|uname|\\/var\\/|\\/root\\/|`|\\$|%0a|%0d|\\r|\\n) [NC,OR]
# Redirect command injection to warning page
RewriteRule ^(.*)$ https://www.miralishahidi.ir/warning.php?blocked=cmd [R=301,L,QSA,E=blocked:cmd]
# Block advanced XSS and JavaScript attempts (events, eval, etc.)
RewriteCond %{QUERY_STRING} (javascript:|\<img|\<svg|\<form|\<input|\<style|\<link|\<meta|onerror|onload|onclick|onmouseover|onfocus|onblur|vbscript:|data:|base64|eval|document\\.cookie|location\\.href|innerHTML|outerHTML|appendChild|insertAdjacentHTML) [NC,OR]
# Redirect advanced XSS to warning page
RewriteRule ^(.*)$ https://www.miralishahidi.ir/warning.php?blocked=advxss [R=301,L,QSA,E=blocked:advxss]
# Limit HTTP methods to safe ones only (GET, POST, HEAD, OPTIONS) - OWASP best practice
RewriteCond %{REQUEST_METHOD} !^(GET|POST|HEAD|OPTIONS) [NC]
# Block unsupported methods with 405 Method Not Allowed
RewriteRule .* - [F,L,E=method_not_allowed:1]
# Block access to sensitive files (e.g., config files, backups) - OWASP recommendation
RewriteRule ^(wp-config\\.php|\\.env|php\\.ini|phpinfo\\.php|\\.htaccess|\\.htpasswd|debug\\.log|error_log|config\\.php|database\\.sql|backup\\.sql|dump\\.sql)$ - [F,L]
RewriteRule \\.(git|env|bak|swp|old|orig|backup|log|sql|db|ini|conf|cfg)$ - [F,L]
# Block access to system directories (e.g., /proc/, /sys/) to prevent info disclosure
RewriteRule ^(proc|sys|dev|tmp|var|root|etc|bin|sbin|usr|home|boot|mnt|media|opt|srv|lib|lib64)/ - [F,L]
# Prevent hotlinking of images and files (protect bandwidth and resources)
RewriteCond %{HTTP_REFERER} !^$ [NC]
RewriteCond %{HTTP_REFERER} !^https?://(www\\.)?(miralishahidi\\.ir|google\\.com|bing\\.com|yahoo\\.com) [NC]
RewriteCond %{HTTP_REFERER} !^https?://([^.]\\+\\.)?(google|bing|yahoo|facebook|twitter|instagram)\\. [NC]
RewriteRule \\.(jpg|jpeg|png|gif|svg|webp|ico|css|js|pdf|zip|rar|exe|mp3|mp4|avi|mov)$ - [F,L]
# Force HTTPS redirect (essential for security, OWASP Top 10 mitigation)
RewriteCond %{HTTPS} !on [NC]
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Block malicious User-Agents (scanners, bots like Nikto, SQLMap)
RewriteCond %{HTTP_USER_AGENT} (libwww-perl|GetRight|wget|WebZIP|HTTrack|libcurl|python|scan|jmeter|webcopier|curl|nikto|sqlmap|john|hydra|medusa|w3af|skipfish|dirbuster|zap|burp|nmap|masscan|zmap|sqlninja|havij|paros|webscarab|vega|acunetix|nessus|openvas|metasploit|maltego|theharvester|dnsenum|Fierce|recon-ng|malware|bot|crawl|spider|scraper|harvester|extractor) [NC]
# Block bad bots with 403 Forbidden
RewriteRule .* - [F,L,E=ua_blocked:1]
# Specifically block TRACE method to prevent XST (Cross-Site Tracing) attacks
RewriteCond %{REQUEST_METHOD} ^TRACE$ [NC]
RewriteRule .* - [F,L]
# Limit query string length to prevent DoS attacks (e.g., buffer overflow)
RewriteCond %{QUERY_STRING} !^.{0,255}$
# Block long queries with 414 URI Too Long
RewriteRule .* - [F,L]
# GZIP compression for better performance (if mod_deflate is not used separately)
RewriteCond %{HTTP:Accept-Encoding} (gzip|\\ deflate) [NC]
RewriteCond %{HTTP_USER_AGENT} !Match
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME}\\.gz -f
RewriteRule .* %{REQUEST_FILENAME}\\.gz [L,QSA]
</IfModule>
# Set essential security headers (OWASP Secure Headers Project)
<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=(), fullscreen=(), payment=(), usb=()"
Header always set Cross-Origin-Embedder-Policy "require-corp"
Header always set Cross-Origin-Opener-Policy "same-origin"
Header always set Cross-Origin-Resource-Policy "same-site"
# Uncomment HSTS after ensuring full HTTPS setup
# Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# Content Security Policy (CSP) - Customize based on site needs
# Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; object-src 'none'; frame-ancestors 'self'; base-uri 'self'; form-action 'self';"
# Cache control for static files
<FilesMatch "\\.(css|js|jpg|jpeg|png|gif|webp|ico|svg|ttf|otf|woff|woff2|eot)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
<FilesMatch "\\.(html|htm|xml)$">
Header set Cache-Control "public, max-age=3600"
</FilesMatch>
# Disable ETag header to prevent info leakage
Header unset ETag
</IfModule>
# Enable caching for performance optimization
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 2 days"
# Cache images for 1 year
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
# Cache fonts for 1 year
ExpiresByType font/woff "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType font/ttf "access plus 1 year"
ExpiresByType font/otf "access plus 1 year"
ExpiresByType font/eot "access plus 1 year"
# Cache CSS and JS for 1 month
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"
# Cache PDFs and other documents for 1 month
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
# Cache XML and RSS for 1 hour
ExpiresByType application/xml "access plus 1 hour"
ExpiresByType application/rss+xml "access plus 1 hour"
ExpiresByType application/atom+xml "access plus 1 hour"
ExpiresByType text/xml "access plus 1 hour"
# Cache icons for 1 year
ExpiresByType image/x-icon "access plus 1 year"
</IfModule>
# Enable GZIP compression for text and other compressible types
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE font/otf
ExpiresByType font/opentype "access plus 1 year"
ExpiresByType font/woff "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
# Browser compatibility for compression
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\\.0[678] no-gzip
BrowserMatch \\bMSIE !no-gzip !gzip-only-text/html
BrowserMatch \\bMSI !no-gzip !gzip-only-text/html
Header append Vary User-Agent env=!dont-vary
</IfModule>
# Disable file ETags to reduce info leakage
<FileETag None>
# Protect .htaccess and other sensitive files from direct access
<Files ".htaccess">
Require all denied
</Files>
<FilesMatch "^(debug\\.log|error_log|php\\.ini|phpinfo\\.php|\\.env|config\\.php|database\\.sql|backup.*\\.sql)$">
Require all denied
</FilesMatch>
<Directory ~ "\\.(git|svn|hg)/">
Require all denied
</Directory>
# Block PHP execution in uploads directory (if applicable)
<Directory "uploads">
<Files ~ "\\.php$">
Order allow,deny
Deny from all
</Files>
</Directory>
# Disable directory listing to prevent information disclosure
Options -Indexes
# Disable Server Side Includes (SSI) and CGI for security
Options -Includes -ExecCGI
# Limit request body size to prevent DoS attacks (10MB limit)
LimitRequestBody 10485760
# Timeout and KeepAlive settings for DoS protection
Timeout 30
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
# Hide server version and signature for security (set in main config if possible)
ServerTokens Prod
ServerSignature Off
# Custom error pages for better user experience and security
ErrorDocument 400 /warning.php
ErrorDocument 401 /warning.php
ErrorDocument 403 /warning.php
ErrorDocument 404 /404.php
ErrorDocument 500 /warning.php
این بخش از دستورات `RewriteCond` و `RewriteRule` برای فیلتر کردن درخواستهای ورودی استفاده میکند. این قوانین حملات رایج را مسدود میکنند:
این بخش هدرهای پاسخ HTTP را برای کاهش حملات سمت کاربر اضافه میکند:
نکته: هدرهای HSTS و CSP را پس از سفارشیسازی و تست کامل فعال کنید.
زمان انقضای فایلها را برای کش مرورگر تنظیم میکند و باعث کاهش بار سرور میشود:
پاسخهای متنی را برای صرفهجویی در پهنای باند فشرده میکند.
این پیکربندی .htaccess یک لایه حفاظتی و بهینهسازی قدرتمند فراهم میکند. با توجه به تخصص من در **امنیت سایبری و تست نفوذ**، این کد به گونهای طراحی شده که با اصول و استانداردهای بینالمللی مانند OWASP همخوانی داشته باشد. برای نیازهای پیشرفتهتر، میتوانید از ابزارهایی مانند ModSecurity یا WAFهای ابری استفاده کنید.