.htaccess guide for Apache web hosting DirectAdmin

The .htaccess file is one of the most powerful tools available on Apache-based hosting. Whether you run WordPress, a PHP application, or a static website on shared hosting with DirectAdmin, understanding .htaccess can help you control redirects, improve security, boost performance, and customize error pages — all without touching the main server configuration.

Table of Contents

  1. What is .htaccess and How Does It Work?
  2. Finding and Creating .htaccess on DirectAdmin
  3. Redirects: 301, 302, and Domain Redirects
  4. URL Rewriting with mod_rewrite
  5. Block Directory Listing and File Access
  6. Custom Error Pages (404, 403, 500)
  7. Speed Up with GZIP and Browser Caching
  8. Configure PHP Settings via .htaccess
  9. Security Headers and Hotlink Protection
  10. Essential .htaccess Rules for WordPress
  11. Summary: .htaccess Commands Reference Table

What is .htaccess and How Does It Work?

.htaccess (Hypertext Access) is a directory-level configuration file for Apache Web Server — the most common web server used on shared hosting and DirectAdmin-based environments. The filename begins with a dot (.), making it a hidden file on Linux systems.

When Apache receives a request for any resource, it reads all .htaccess files found along the directory path, from the root down to the requested file's directory, applying each file's directives on top of the main server configuration. This lets you customize server behavior per directory without server-level admin access.

Key advantage: No Apache restart required. Changes to .htaccess take effect on the next request automatically — save the file and the new rules are live immediately.

Supported by: Apache httpd, LiteSpeed (Apache-compatible syntax) · Not supported by: Nginx (Nginx uses its own configuration system)

Finding and Creating .htaccess on DirectAdmin Hosting

On DirectAdmin Hosting, the main .htaccess file lives at /home/username/domains/yourdomain.com/public_html/.htaccess. You can access it three ways:

⚠️ Important: Always backup your existing .htaccess before editing. A single syntax error will cause a 500 Internal Server Error for your entire site. Keep the original in a safe place so you can restore it if something breaks.

If no .htaccess file exists yet, create one via File Manager: click "Create File" and name it .htaccess (starting with a dot, no extension).

Redirects: 301, 302, and Domain Redirects

Redirects are among the most common .htaccess uses. There are two main types:

301 Redirect (Permanent)

Use for permanent URL changes — Google passes PageRank to the new URL, making 301 redirects essential for SEO when you move pages or change domains.

# Redirect a single page (301 permanent)
Redirect 301 /old-page.html https://www.example.com/new-page.html

# Force HTTPS (HTTP → HTTPS)
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# Redirect non-www to www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

302 Redirect (Temporary)

Use for temporary redirects (e.g., maintenance pages). Google does not pass PageRank for 302 redirects.

Redirect 302 /maintenance.html https://www.example.com/under-construction.html

URL Rewriting with mod_rewrite

mod_rewrite is Apache's powerful URL manipulation engine. It lets you create clean, SEO-friendly URLs without changing your actual file structure.

RewriteEngine On

# Clean URL: /product/123 → /product.php?id=123
RewriteRule ^product/([0-9]+)/?$ product.php?id=$1 [L,QSA]

# Hide .php extension: /about → /about.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)/?$ $1.php [L]

# Block direct access to .log files
RewriteRule \.log$ - [F,L]

Common flags: [L] = Last rule (stop processing) · [R=301] = Redirect with status code · [QSA] = Append query string · [F] = Forbidden (403) · [NC] = Case-insensitive · [NE] = No escape

Block Directory Listing and File Access

By default, Apache may show a directory listing if no index file exists in a folder. This is a security risk that exposes your file structure.

# Disable directory browsing
Options -Indexes

# Block access to sensitive files
<Files ".env">
    Order allow,deny
    Deny from all
</Files>

# Block multiple file types at once
<FilesMatch "\.(log|bak|sql|old|zip|tar\.gz)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# Protect .htaccess itself
<Files ".htaccess">
    Order allow,deny
    Deny from all
</Files>

Custom Error Pages (404, 403, 500)

Replace Apache's default ugly error pages with custom pages that maintain your site's design and help visitors find what they need.

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

# Or redirect to a specific page for 404
ErrorDocument 404 https://www.example.com/not-found.html

Create your custom error HTML files in an errors/ folder (or any folder you choose) and design them with navigation links back to key pages for better user experience.

Speed Up with GZIP and Browser Caching

Enable GZIP Compression

GZIP compresses files before sending them to the browser. For HTML, CSS, and JavaScript files, this typically reduces file size by 60–80%, dramatically improving load times.

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/css
    AddOutputFilterByType DEFLATE text/javascript application/javascript
    AddOutputFilterByType DEFLATE application/json application/xml
    AddOutputFilterByType DEFLATE image/svg+xml
    # Don't compress already-compressed files
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|webp|gz|zip)$ no-gzip
</IfModule>

Browser Caching (Expires Headers)

Tell browsers to cache static files locally. Returning visitors load your site from cache instead of re-downloading everything, significantly improving performance.

<IfModule mod_expires.c>
    ExpiresActive On
    # Images — cache for 1 year
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    # CSS and JS — cache for 1 month
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    # HTML — cache for 1 day
    ExpiresByType text/html "access plus 1 day"
    # Fonts — cache for 1 year
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType font/woff "access plus 1 year"
</IfModule>

Configure PHP Settings via .htaccess

On shared hosting where you can't directly edit php.ini, you can override certain PHP settings through .htaccess (when PHP runs as an Apache module):

# Increase memory and upload limits
php_value memory_limit 256M
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300

# Disable error display for production
php_flag display_errors Off
php_flag log_errors On
php_value error_log /home/user/logs/php_errors.log

Note: php_value in .htaccess only works when PHP runs as an Apache module (mod_php). If your server uses PHP-FPM, use a .user.ini file instead with the same syntax (without the php_value/php_flag prefixes).

Security Headers and Hotlink Protection

Add Security Response Headers

HTTP security headers instruct browsers on how to handle your content, protecting against common attacks like XSS and clickjacking.

<IfModule mod_headers.c>
    # Prevent clickjacking
    Header always set X-Frame-Options "SAMEORIGIN"
    # Prevent MIME-type sniffing
    Header always set X-Content-Type-Options "nosniff"
    # Force HTTPS with HSTS
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    # Control referrer information
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    # Legacy XSS protection
    Header always set X-XSS-Protection "1; mode=block"
</IfModule>

Hotlink Protection

Prevent other websites from embedding your images directly (bandwidth theft). Requests where the Referer header doesn't match your domain will be blocked.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com/ [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,L]

Essential .htaccess Rules for WordPress

WordPress relies on .htaccess for its permalink system. WordPress creates these rules automatically, but if they're missing or corrupted, you'll get 404 errors on all pages except the homepage:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Additional recommended WordPress security rules:

# Protect wp-config.php
<Files wp-config.php>
    Order allow,deny
    Deny from all
</Files>

# Block XML-RPC (prevents brute force attacks)
<Files xmlrpc.php>
    Order allow,deny
    Deny from all
</Files>

# Protect wp-includes from direct PHP execution
RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]

Summary: .htaccess Commands Reference Table

Directive Purpose Example
Redirect 301 Permanent redirect Redirect 301 /old /new-url
RewriteEngine On Enable mod_rewrite Required before all RewriteRule directives
RewriteRule URL rewriting RewriteRule ^old/(.*)$ new/$1 [R=301,L]
Options -Indexes Disable directory listing Prevents file list exposure
ErrorDocument Custom error pages ErrorDocument 404 /404.html
php_value Override PHP settings (mod_php) php_value memory_limit 256M
AddOutputFilterByType DEFLATE Enable GZIP compression Compress HTML/CSS/JS responses
ExpiresByType Set browser cache lifetime ExpiresByType image/jpeg "access plus 1 year"
Header always set Add security headers Header always set X-Frame-Options "SAMEORIGIN"

Need Hosting That Fully Supports .htaccess?

AsiaGB Hosting runs Apache + DirectAdmin with full .htaccess support (AllowOverride All), SSD storage, 99% Uptime SLA, and English-language support.

View Hosting Plans