.htaccess commands for Apache Web Server on hosting

📋 Table of Contents

  1. What is .htaccess and How Does It Work
  2. File Location and Permissions
  3. URL Redirects — 301 and 302
  4. URL Rewriting with mod_rewrite
  5. Disable Directory Listing
  6. Custom Error Pages
  7. Force HTTPS
  8. Hotlink Protection
  9. Browser Caching
  10. Basic Security with .htaccess
  11. Troubleshooting .htaccess Issues
  12. Frequently Asked Questions

The .htaccess file is one of the most powerful tools available to hosting users. Whether you need to redirect URLs, improve security, enforce HTTPS, or boost performance — all of it is achievable through this single configuration file. This guide covers the most commonly used commands with practical, copy-paste-ready code examples.

1. What is .htaccess and How Does It Work

.htaccess (Hypertext Access) is a configuration file for the Apache Web Server that controls server behavior at the directory level. The dot prefix makes it a hidden file in most operating systems. You can have one .htaccess file per directory, and it applies to that directory and all subdirectories below it.

When Apache receives a request, it reads .htaccess files from the root down to the target directory, applying all rules along the way. The key advantage: changes take effect immediately — no server restart required.

What .htaccess Can Do

FeatureCommon Use Case
URL RedirectOld domain → new domain, 301/302 redirects
URL RewritingPretty URLs: /product?id=5 → /product/5
Directory ListingPrevent browsing folder contents
Custom Error PagesBranded 404 and 500 error pages
Force HTTPSAuto-redirect all HTTP to HTTPS
Hotlink ProtectionStop bandwidth theft via image hotlinking
Browser CachingSpeed up pages with cache headers
SecurityBlock file access, add security headers
💡 Good to Know

AsiaGB Hosting uses Apache with mod_rewrite enabled by default. You can use .htaccess features immediately without any special setup.

2. File Location and Permissions

Place your .htaccess file in the directory you want to control. For site-wide effect, put it in your web root:

/home/username/
└── public_html/
    ├── .htaccess     ← affects entire site
    ├── index.php
    └── admin/
        └── .htaccess ← affects only /admin/

Correct permission: 644 (owner read/write, others read-only). Never set 777 — that is a security risk.

Create or edit .htaccess via DirectAdmin → File Manager (enable Show Hidden Files), or upload via FTP using FileZilla or similar clients.

3. URL Redirects — 301 and 302

Redirects are the most common .htaccess use case — essential when changing domains, restructuring URLs, or moving content.

301 Permanent Redirect

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

# Redirect entire old domain to new domain
RewriteEngine On
RewriteCond %{HTTP_HOST} ^oldsite\.com$ [NC]
RewriteRule ^(.*)$ https://newsite.com/$1 [L,R=301]

302 Temporary Redirect

Redirect 302 /promo.html https://example.com/sale.html
⚠️ Important

Use 301 only for permanent moves. Browsers and Google cache 301s aggressively — once served, it can take weeks to undo even if you remove the redirect rule.

Force www / Remove www

# Force www
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [L,R=301]

# Remove www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [L,R=301]

4. URL Rewriting with mod_rewrite

URL rewriting transforms "ugly" dynamic URLs into clean, readable ones — better for users and search engines.

Enable mod_rewrite

RewriteEngine On
RewriteBase /

Example: WordPress Permalink Support

# BEGIN WordPress
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

Example: Remove .php Extension from URLs

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/?$ $1.php [L]

Example: Clean Product URLs

# /product?id=5 → /product/5
RewriteEngine On
RewriteRule ^product/([0-9]+)/?$ product.php?id=$1 [L,QSA]
FlagMeaning
[L]Last — stop processing further rules
[R=301]Redirect with status code
[NC]No Case — case-insensitive matching
[QSA]Query String Append — preserve existing query string
[NE]No Escape — don't escape special characters

5. Disable Directory Listing

By default, Apache may show a list of files in directories that have no index file. This exposes your site structure and is a security risk.

# Disable directory browsing for entire site
Options -Indexes
✅ Best Practice

Always add Options -Indexes to your root .htaccess. It's one of the simplest yet most effective security measures.

6. Custom Error Pages

Replace the default server error pages with custom, on-brand pages that keep users on your site.

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
Error CodeMeaningCommon Cause
400Bad RequestMalformed request syntax
403ForbiddenNo permission to access resource
404Not FoundPage doesn't exist
500Internal Server ErrorCode or config error
503Service UnavailableServer temporarily overloaded

7. Force HTTPS

Enforcing HTTPS is essential for security, user trust, and SEO ranking signals.

# Standard server (no load balancer)
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Behind a load balancer or reverse proxy (e.g. Cloudflare)
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
ℹ️ Note

You must install an SSL certificate before forcing HTTPS. AsiaGB Hosting users can get a free Let's Encrypt certificate directly through DirectAdmin.

Hotlinking is when other websites embed your images directly from your server, consuming your bandwidth without benefit.

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

Replace yourdomain.com with your domain. This returns 403 Forbidden when external sites try to hotlink your images.

9. Browser Caching

Browser caching tells visitors' browsers to store static files locally, dramatically improving load times on repeat visits — directly impacting Core Web Vitals scores.

<IfModule mod_expires.c>
  ExpiresActive On

  # Images — cache 1 year
  ExpiresByType image/jpg "access plus 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"
  ExpiresByType image/svg+xml "access plus 1 year"
  ExpiresByType image/x-icon "access plus 1 year"

  # CSS and JS — cache 1 month
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"

  # Fonts — cache 1 year
  ExpiresByType font/woff2 "access plus 1 year"
  ExpiresByType application/font-woff2 "access plus 1 year"

  # HTML — short cache (to allow quick updates)
  ExpiresByType text/html "access plus 1 hour"
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(jpg|jpeg|png|webp|gif|ico|css|js|woff|woff2)$">
    Header set Cache-Control "public, max-age=31536000"
  </FilesMatch>
</IfModule>

10. Basic Security with .htaccess

These security directives should be in every website's .htaccess file.

Hide Server Information

ServerSignature Off

<IfModule mod_headers.c>
  Header unset X-Powered-By
  Header always unset X-Powered-By
</IfModule>

Add Security Headers

<IfModule mod_headers.c>
  Header always set X-Frame-Options "SAMEORIGIN"
  Header always set X-XSS-Protection "1; mode=block"
  Header always set X-Content-Type-Options "nosniff"
  Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
  Header always set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

Protect Sensitive Files

# Protect .htaccess and .htpasswd
<FilesMatch "^\.ht">
  Require all denied
</FilesMatch>

# Block common backup file extensions
<FilesMatch "\.(bak|backup|sql|log|old|orig)$">
  Require all denied
</FilesMatch>

# Protect WordPress config
<Files "wp-config.php">
  Require all denied
</Files>

Restrict HTTP Methods

<LimitExcept GET POST HEAD>
  Require all denied
</LimitExcept>

11. Troubleshooting .htaccess Issues

⚠️ 500 Error After Saving .htaccess

If your site shows a 500 Internal Server Error immediately after saving .htaccess, there is a syntax error. Check each line carefully — a misplaced comment (#) inside a directive or missing space can break the file.

ProblemLikely CauseFix
Redirect not workingMissing RewriteEngine OnAdd RewriteEngine On before any RewriteRule
Redirect loopMissing HTTPS conditionAdd RewriteCond to check %{HTTPS} first
All URLs return 404Wrong RewriteBaseSet RewriteBase to match your actual path
Caching not workingmod_expires not loadedUse mod_headers instead, or contact support
Security headers missingmod_headers not loadedVerify enabled Apache modules

12. Frequently Asked Questions

What is .htaccess and what can it do?

.htaccess is an Apache Web Server configuration file that controls server behavior at the directory level without modifying the main server config. It handles URL redirects, rewriting, directory listing protection, custom error pages, HTTPS enforcement, hotlink protection, browser caching, and security headers.

Where should I place the .htaccess file on my hosting?

Place it in your public_html/ directory for site-wide effect, or in any subdirectory to control only that folder. Create or edit it in the DirectAdmin File Manager (enable Show Hidden Files) or upload via FTP.

Why is my .htaccess not working?

Most common causes: AllowOverride set to None in Apache config, mod_rewrite not enabled, incorrect filename (it must be exactly .htaccess), syntax error in the file, or wrong file permissions (should be 644).

What is the difference between 301 and 302 redirects?

301 (Moved Permanently) is for permanent URL changes — Google passes link equity to the new URL and caches the redirect. 302 (Temporary) is for short-term redirects — Google keeps the original URL indexed. Use 301 for all permanent moves, page merges, or domain changes.

Can I use .htaccess on AsiaGB DirectAdmin hosting?

Yes. AsiaGB Hosting runs Apache with mod_rewrite enabled. Create or edit .htaccess files via the DirectAdmin File Manager or FTP — everything works immediately without any extra configuration.

Does .htaccess affect website performance?

The overhead from parsing .htaccess is minimal for most sites. The performance gains from enabling browser caching via .htaccess far outweigh this cost. Sites with many complex RewriteRules may see a slight slowdown, but for typical websites the impact is negligible.

Summary: .htaccess — A Powerful Tool for Every Hosting User

.htaccess gives you fine-grained control over your web server without touching any admin panel settings. From URL management and security hardening to performance optimization, it's an essential part of professional website management.

Recommended baseline for every site:

Hosting with Full .htaccess Support

AsiaGB Hosting runs Apache + DirectAdmin with mod_rewrite fully enabled. SSD storage, 99% Uptime, starting from 500 THB/month.

View Hosting Plans