Stop being intimidated by .htaccess files! Our comprehensive guide covers everything from basic redirects to advanced LiteSpeed configurations. Real examples, common mistakes, and expert tips included.
Ever stared at a .htaccess file and thought “What the hell is this black magic?” You’re not alone.
.htaccess files look like cryptic spells written by caffeinated developers at 3 AM. One wrong character and your entire website disappears into the digital void. One right configuration and suddenly you’re redirecting URLs like a boss, blocking spam bots, and making your site faster than your neighbor’s WiFi.
Here’s the thing: .htaccess isn’t actually that complicated once you understand the basics. It’s just that most tutorials either assume you have a computer science degree or explain it like you’re five years old and can’t handle real examples.
This guide is different. We’ll start with “what the hell is .htaccess” and end with you confidently writing rules that would make senior developers nod in approval. No fluff, no “just copy this code and pray” – actual understanding.
What you’ll master:
Ready to demystify the most powerful configuration file on your server?
.htaccess stands for “Hypertext Access” – it’s basically a configuration file that tells your web server how to behave. Think of it as house rules for your website.
When someone visits your site, the web server (Apache, LiteSpeed, etc.) reads these rules and decides what to do:
The file is literally called .htaccess (with a dot at the beginning), which makes it hidden by default on most systems. This isn’t some conspiracy – it’s a safety feature to prevent casual users from accidentally breaking their sites.
SEO Benefits: Proper redirects preserve your search rankings when you change URLs. Google hates broken links more than we hate Monday mornings.
Security: Block malicious requests before they reach your actual website code. It’s like having a bouncer for your server.
Performance: Control caching and compression to make your site load faster than your competition.
User Experience: Custom error pages instead of ugly server defaults. Professional redirects instead of broken links.
Most .htaccess tutorials focus on Apache, but if you’re on WebHostMost, you’re running LiteSpeed Web Server. Good news: LiteSpeed is designed to be Apache-compatible, so 99% of .htaccess rules work identically.
The difference is performance. LiteSpeed processes .htaccess rules faster and more efficiently than Apache. Your .htaccess configurations don’t just work – they work better.
Your .htaccess file lives in your website’s root directory, which on WebHostMost is typically:
/domains/yourdomain.com/public_html/
Using WebHostMost File Manager:
If you don’t see .htaccess: You might not have one yet. Many CMSs create it automatically, but if your site is custom or static HTML, you might need to create it yourself.
Method 1: Through WebHostMost File Manager
# WebHostMost .htaccess Configuration
# Created: [Today’s Date]
#
# WARNING: Backup this file before making changes!
# Enable RewriteEngine for URL processing
RewriteEngine On
# Your rules go below this line
Method 2: Using FTP/SFTP Download any existing .htaccess file, edit it locally, and upload it back. Always backup the original.
ALWAYS BACKUP BEFORE EDITING.
Seriously. WebHostMost’s documentation emphasizes this because one syntax error can break your entire site. Create a backup copy called .htaccess-backup before making any changes.
.htaccess files are processed line by line, top to bottom. Comments start with # and are ignored by the server:
# This is a comment
RewriteEngine On # This is also a comment
# Block specific IP addresses
Deny from 192.168.1.100
Directives are commands that tell the server what to do. They come in two flavors:
Simple Directives: One command per line
ErrorDocument 404 /custom-404.html
DirectoryIndex index.html index.php
Module-Based Directives: Grouped under specific modules
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^old$ /new [R=301,L]
</IfModule>
mod_rewrite: URL manipulation and redirects
RewriteEngine On
RewriteRule pattern substitution [flags]
mod_alias: Simple redirects and aliases
Redirect 301 /old-page /new-page
mod_access: Access control
Order Allow,Deny
Allow from all
Deny from 192.168.1.100
301 (Permanent Redirect): “This page has moved forever”
302 (Temporary Redirect): “This page is temporarily elsewhere”
307 (Temporary Redirect, Method Preserved): Like 302 but stricter
For basic redirects, use the Redirect directive:
# Redirect single page
Redirect 301 /old-page.html /new-page.html
# Redirect to external domain
Redirect 301 /old-section https://example.com/new-section
# Redirect entire directory
Redirect 301 /old-directory/ /new-directory/
When you need more control, use mod_rewrite:
RewriteEngine On
# Redirect with pattern matching
RewriteRule ^products/([0-9]+)/?$ /item/$1 [R=301,L]
# This redirects /products/123 to /item/123
# Redirect all PHP files to HTML
RewriteRule ^(.*)\.php$ /$1.html [R=301,L]
Force HTTPS (SSL):
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Force WWW subdomain:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Remove WWW subdomain:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [L,R=301]
Add trailing slash:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [R=301,L]
Block specific IP addresses:
# Block single IP
<RequireAll>
Require all granted
Require not ip 192.168.1.100
</RequireAll>
# Block IP range
<RequireAll>
Require all granted
Require not ip 192.168.1
</RequireAll>
Block by user agent:
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} “badbot” [NC]
RewriteRule .* – [F,L]
Block by referrer:
RewriteEngine On
RewriteCond %{HTTP_REFERER} “spamsite\.com” [NC]
RewriteRule .* – [F,L]
Hide .htaccess from web access:
<Files “.htaccess”>
Require all denied
</Files>
Protect backup files:
<FilesMatch “\.(bak|backup|old|tmp)$”>
Require all denied
</FilesMatch>
Block access to specific directories:
<DirectoryMatch “/(config|cache|logs)/”>
Require all denied
</DirectoryMatch>
# Prevent MIME type sniffing
Header always set X-Content-Type-Options nosniff
# Enable XSS protection
Header always set X-XSS-Protection “1; mode=block”
# Prevent clickjacking
Header always set X-Frame-Options DENY
# Force HTTPS for 1 year
Header always set Strict-Transport-Security “max-age=31536000; includeSubDomains”
# Content Security Policy (basic)
Header always set Content-Security-Policy “default-src ‘self'”
LiteSpeed Web Server powers WebHostMost hosting because it’s faster and more efficient than traditional Apache. WebHostMost’s infrastructure is optimized for LiteSpeed, which means your .htaccess configurations perform better by default.
# Enable LiteSpeed Cache
<IfModule Litespeed>
# Cache static files for 1 week
RewriteRule \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ – [E=Cache-Control:max-age=604800]
# Cache HTML for 1 hour
RewriteRule \.html$ – [E=Cache-Control:max-age=3600]
</IfModule>
PHP Configuration through .htaccess:
# Set PHP memory limit
php_value memory_limit 256M
# Set maximum execution time
php_value max_execution_time 300
# Enable PHP error reporting (development only!)
php_flag display_errors On
php_flag log_errors On
WebHostMost-specific optimizations:
# Enable compression for better performance
<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
</IfModule>
Instead of ugly server error pages, create custom ones:
# Custom error pages
ErrorDocument 400 /errors/400.html
ErrorDocument 401 /errors/401.html
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html
Your custom error pages should:
# Disable directory browsing
Options -Indexes
# Enable directory browsing (usually not recommended)
Options +Indexes
# Custom index files
DirectoryIndex index.html index.php home.html
# Add custom MIME types
AddType application/pdf .pdf
AddType audio/mpeg .mp3
AddType video/mp4 .mp4
# Force download for certain file types
<FilesMatch “\.(pdf|doc|docx|zip)$”>
Header set Content-Disposition attachment
</FilesMatch>
Prevent other sites from stealing your images:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|bmp|svg)$ /images/no-hotlink.png [R,L]
WordPress automatically generates this when you enable pretty permalinks:
# BEGIN WordPress
RewriteEngine On
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
Never edit between the # BEGIN WordPress and # END WordPress comments! WordPress overwrites this section automatically.
Add these ABOVE the WordPress section:
# Protect wp-config.php
<files wp-config.php>
Require all denied
</files>
# Limit login attempts
<files wp-login.php>
# Only allow access from your IP
<RequireAll>
Require ip YOUR.IP.ADDRESS.HERE
Require all denied
</RequireAll>
</files>
# Block access to sensitive files
<FilesMatch “^(wp-config\.php|readme\.html|license\.txt)”>
Require all denied
</FilesMatch>
# Disable XML-RPC (prevents brute force attacks)
<files xmlrpc.php>
Require all denied
</files>
# Browser caching for WordPress
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg “access plus 1 month”
ExpiresByType image/jpeg “access plus 1 month”
ExpiresByType image/gif “access plus 1 month”
ExpiresByType image/png “access plus 1 month”
ExpiresByType text/css “access plus 1 month”
ExpiresByType application/pdf “access plus 1 month”
ExpiresByType text/javascript “access plus 1 month”
ExpiresByType application/javascript “access plus 1 month”
ExpiresByType text/html “access plus 5 minutes”
</IfModule>
500 Internal Server Error: This is usually a syntax error in your .htaccess file.
# Wrong (causes 500 error):
RewriteRule ^old new [R=301,L # Missing closing bracket
# Right:
RewriteRule ^old new [R=301,L]
Common syntax mistakes:
WebHostMost’s troubleshooting guide covers this in detail, but common causes include:
Quick fix checklist:
# Check file permissions
# public_html should be 755
# .htaccess should be 644
# index files should be 644
# Verify index file exists
DirectoryIndex index.html index.php
# Test with minimal .htaccess
RewriteEngine On
# Add other rules one by one
Use online .htaccess testers:
Test locally first:
Monitor server logs:
.htaccess files are processed for every request, so optimization matters:
Good practices:
# Use IfModule to prevent errors
<IfModule mod_rewrite.c>
RewriteEngine On
# Your rewrite rules here
</IfModule>
# Group similar rules together
# Put most common rules first
# Use specific patterns instead of broad ones
Avoid these performance killers:
# Bad: Processes for every request
RewriteCond %{REQUEST_URI} !^/admin/
RewriteRule ^(.*)$ /redirect.php?url=$1
# Better: More specific matching
RewriteRule ^old-section/(.*)$ /new-section/$1 [R=301,L]
Always use HTTPS redirects:
# Use https:// in redirect targets
RewriteRule ^old$ https://yourdomain.com/new [R=301,L]
Validate user input in redirects:
# Bad: Could redirect to malicious sites
RewriteRule ^redirect/(.*)$ $1 [R=301,L]
# Good: Validate the destination
RewriteRule ^redirect/page([0-9]+)$ /page.php?id=$1 [R=301,L]
Keep sensitive data out of .htaccess:
# Bad: API keys visible in .htaccess
SetEnv API_KEY “secret123”
# Good: Use environment variables or config files
# Set sensitive data in your hosting control panel
Document your rules:
# Force HTTPS redirect
# Added: 2025-01-15
# Purpose: Improve SEO and security
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Use consistent formatting:
# Good: Consistent indentation and spacing
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^old$ /new [R=301,L]
RewriteRule ^test$ /demo [R=301,L]
</IfModule>
Version control your .htaccess: Keep backups and track changes over time.
Scenario: Moving from /product.php?id=123 to /products/product-name-123
RewriteEngine On
# Redirect old product URLs to new structure
RewriteCond %{QUERY_STRING} ^id=([0-9]+)$
RewriteRule ^product\.php$ /products/product-%1? [R=301,L]
# Handle new URL structure
RewriteRule ^products/product-([0-9]+)/?$ /product.php?id=$1 [L]
Scenario: Moving from Blogger to WordPress
RewriteEngine On
# Redirect Blogger post URLs
RewriteRule ^([0-9]{4})/([0-9]{2})/(.*)\.html$ /$1/$2/$3/ [R=301,L]
# Redirect archive pages
RewriteRule ^([0-9]{4})/([0-9]{2})/?$ /$1/$2/ [R=301,L]
# Redirect search pages
RewriteRule ^search\?q=(.*)$ /?s=$1 [R=301,L]
Scenario: Moving from olddomain.com to newdomain.com/blog
RewriteEngine On
# Redirect all old domain traffic
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
RewriteRule ^(.*)$ https://newdomain.com/blog/$1 [R=301,L]
Scenario: Implementing language-based redirects
RewriteEngine On
# Detect browser language and redirect
RewriteCond %{HTTP:Accept-Language} ^en [NC]
RewriteRule ^$ /en/ [R=302,L]
RewriteCond %{HTTP:Accept-Language} ^es [NC]
RewriteRule ^$ /es/ [R=302,L]
RewriteCond %{HTTP:Accept-Language} ^fr [NC]
RewriteRule ^$ /fr/ [R=302,L]
# Default to English
RewriteRule ^$ /en/ [R=302,L]
# Set environment variables
SetEnv CUSTOM_VAR “production”
# Use in conditions
RewriteCond %{ENV:CUSTOM_VAR} ^production$
RewriteRule ^admin/ – [F]
RewriteEngine On
# Multiple conditions (AND logic – default)
RewriteCond %{REQUEST_METHOD} ^POST$ [NC]
RewriteCond %{CONTENT_TYPE} !^multipart/form-data [NC]
RewriteRule ^upload/ – [F]
# Multiple conditions (OR logic)
RewriteCond %{REMOTE_ADDR} ^192\.168\.1\. [NC,OR]
RewriteCond %{REMOTE_ADDR} ^10\.0\.0\. [NC]
RewriteRule ^admin/ – [E=ADMIN_ACCESS:1]
# Handle AJAX requests differently
RewriteCond %{HTTP:X-Requested-With} ^XMLHttpRequest$ [NC]
RewriteRule ^api/(.*)$ /ajax-handler.php?endpoint=$1 [L,QSA]
# Regular requests
RewriteRule ^api/(.*)$ /regular-handler.php?endpoint=$1 [L,QSA]
# Simple load balancing between servers
RewriteEngine On
RewriteRule ^(.*)$ http://server1.example.com/$1 [P,L,E=server:1]
# Failover configuration
RewriteCond %{ENV:server} !^1$
RewriteRule ^(.*)$ http://server2.example.com/$1 [P,L]
Create a test checklist:
# Test these scenarios after any .htaccess change:
# 1. Homepage loads correctly
# 2. SSL redirect works
# 3. www redirect works
# 4. 404 pages show custom error
# 5. Admin areas are protected
# 6. Images load correctly
# 7. No redirect loops
# Test redirect
curl -I https://yourdomain.com/old-page
# Should return:
# HTTP/1.1 301 Moved Permanently
# Location: https://yourdomain.com/new-page
Google Search Console:
Server log analysis:
# Enable detailed logging (temporarily)
LogLevel rewrite:trace3
# Redirect 50% of traffic to new version
RewriteEngine On
RewriteCond %{TIME_SEC} [02468]$
RewriteRule ^test-page$ /new-version.html [R=302,L]
RewriteRule ^test-page$ /old-version.html [R=302,L]
.htaccess files aren’t magic – they’re just instructions for your web server. Like any tool, they’re powerful when used correctly and dangerous when used carelessly.
The key principles to remember:
For WebHostMost users specifically: Your LiteSpeed infrastructure processes .htaccess rules efficiently, and the comprehensive documentation provides LiteSpeed-specific guidance when you need it.
Common beginner mistakes to avoid:
When to get help: If you’re making changes that could affect your entire site (domain migrations, major redirects), consider working with a developer or at least testing extensively on a staging environment first.
The productivity mindset: Don’t try to learn everything at once. Master redirects first, then add security rules, then optimize for performance. Each skill builds on the previous one.
Your .htaccess file is one of the most powerful tools for controlling your website’s behavior. With WebHostMost’s reliable LiteSpeed infrastructure and the knowledge from this guide, you’re equipped to use it effectively.
Ready to stop copy-pasting random .htaccess code from Stack Overflow and start understanding what you’re actually doing? Your website (and your stress levels) will thank you.
Need help implementing these .htaccess configurations?
Check out WebHostMost’s blog and documentation for LiteSpeed-specific guidance and expert support.