.htaccess is a powerful configuration file that controls how your server handles requests.
What is .htaccess?
The .htaccess file lets you configure server behavior without editing main configuration files. It affects the directory it's in and all subdirectories.
Locate or Create .htaccess
- Open cPanel File Manager
- Navigate to public_html
- Click Settings and check "Show Hidden Files"
- Look for .htaccess (create one if it doesn't exist)
Common Configurations
Force HTTPS
Redirect all traffic to HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Redirect www to non-www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
Redirect non-www to www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
Custom Error Pages
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
Block IP Address
Deny from 123.456.789.0
Password Protect Directory
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/username/.htpasswds/public_html/admin/passwd
Require valid-user
Enable GZIP Compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
Set Browser Caching
<IfModule mod_expires.c>
ExpiresActive On
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 text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
Safety Tips
- Always back up .htaccess before editing
- Test after each change
- A single syntax error can crash your site
- Remove .htaccess to restore if site breaks
WordPress Note
WordPress creates its own .htaccess for permalinks. Add your custom rules above or below the WordPress section, not inside it.
Tags:#htaccess#redirect#server#configuration