📋 Table of Contents
- What is .htaccess and How Does It Work
- File Location and Permissions
- URL Redirects — 301 and 302
- URL Rewriting with mod_rewrite
- Disable Directory Listing
- Custom Error Pages
- Force HTTPS
- Hotlink Protection
- Browser Caching
- Basic Security with .htaccess
- Troubleshooting .htaccess Issues
- 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
| Feature | Common Use Case |
|---|---|
| URL Redirect | Old domain → new domain, 301/302 redirects |
| URL Rewriting | Pretty URLs: /product?id=5 → /product/5 |
| Directory Listing | Prevent browsing folder contents |
| Custom Error Pages | Branded 404 and 500 error pages |
| Force HTTPS | Auto-redirect all HTTP to HTTPS |
| Hotlink Protection | Stop bandwidth theft via image hotlinking |
| Browser Caching | Speed up pages with cache headers |
| Security | Block file access, add security headers |
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
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]
| Flag | Meaning |
|---|---|
| [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
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 Code | Meaning | Common Cause |
|---|---|---|
| 400 | Bad Request | Malformed request syntax |
| 403 | Forbidden | No permission to access resource |
| 404 | Not Found | Page doesn't exist |
| 500 | Internal Server Error | Code or config error |
| 503 | Service Unavailable | Server 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]
You must install an SSL certificate before forcing HTTPS. AsiaGB Hosting users can get a free Let's Encrypt certificate directly through DirectAdmin.
8. Hotlink Protection
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
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.
| Problem | Likely Cause | Fix |
|---|---|---|
| Redirect not working | Missing RewriteEngine On | Add RewriteEngine On before any RewriteRule |
| Redirect loop | Missing HTTPS condition | Add RewriteCond to check %{HTTPS} first |
| All URLs return 404 | Wrong RewriteBase | Set RewriteBase to match your actual path |
| Caching not working | mod_expires not loaded | Use mod_headers instead, or contact support |
| Security headers missing | mod_headers not loaded | Verify 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:
- Add
Options -Indexesto disable directory listing - Force HTTPS with a 301 redirect rule
- Set up custom 404 and 500 error pages
- Add security headers to block XSS and clickjacking
- Configure browser caching for static assets
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