
.htaccess (Hypertext Access) is a small configuration file placed inside your website's folder that issues commands directly to the Apache web server. Its strength is letting you change site behaviour without editing the main server config or having root access — making it an essential tool for shared hosting users. This guide collects the most commonly used .htaccess directives, from redirects and IP blocking to security settings.
How to Access and Edit .htaccess
- Open File Manager in DirectAdmin
- Navigate to the
public_htmlfolder - Enable Show Hidden Files to make .htaccess visible
- Click Edit to modify it, or create a new file if none exists
301 and 302 Redirects
Use these to forward visitors from one URL to another:
301 Permanent Redirect (recommended for SEO):
Redirect 301 /old-page.html https://www.yourdomain.com/new-page/
302 Temporary Redirect:
Redirect 302 /promo.html https://www.yourdomain.com/sale/
Force HTTPS
Add these lines to force all HTTP traffic to use HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Block Unwanted IP Addresses
Deny access from specific IPs or IP ranges:
Order allow,deny
Deny from 192.168.1.1
Deny from 10.0.0.0/8
Allow from all
Password Protect a Directory
Restrict a folder with a username and password — useful for admin areas or staging sites:
AuthType Basic
AuthName "Protected Area"
AuthUserFile /home/username/.htpasswd
Require valid-user
Cache-Control Headers
Set browser caching to speed up static file delivery:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
Custom Error Pages
Replace Apache's default error pages with your own:
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
Ready-to-Use .htaccess Snippets by Purpose
The sections above showed directives one line at a time. Here we group the most useful commands into complete, copy-paste blocks you can drop straight into .htaccess on AsiaGB's Apache + DirectAdmin hosting. Just adjust the domain and paths to match your own site. Each block works independently, so you can use one or combine several.
1. Enforce www or non-www Consistently
Pick exactly one block so every URL points to a single canonical form — this consolidates SEO signals and prevents duplicate content:
# Force non-www (example.com)
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [L,R=301]
# Or force www (www.example.com)
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [L,R=301]
2. Force HTTPS With HSTS
Building on the Force HTTPS section above, this combines the HTTPS redirect with an HSTS header so browsers remember to always use HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Tell browsers to use HTTPS for at least one year
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>
3. A Full Set of Custom Error Pages
Define branded error pages for every common status code so users stay on-brand and can find their way forward:
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
4. Block IPs, User-Agents and Unwanted Bots
Beyond blocking individual IPs, you can block bad bots by User-Agent to cut server load and content scraping:
# Block IPs and ranges (Apache 2.4 syntax)
<RequireAll>
Require all granted
Require not ip 192.168.1.50
Require not ip 203.0.113.0/24
</RequireAll>
# Block bots by User-Agent name
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (AhrefsBot|MJ12bot|SemrushBot|DotBot) [NC]
RewriteRule .* - [F,L]
5. Protect Sensitive Files and Disable Listing
Hide sensitive config files and turn off directory listing so visitors never see a file index when there is no index page:
# Disable directory listing
Options -Indexes
# Block dotfiles and config files
<FilesMatch "^\.|\.(env|ini|log|sql|bak)$">
Require all denied
</FilesMatch>
6. Set Caching (Expires) and Gzip Compression
These two blocks noticeably speed up a site: Expires reduces repeat downloads of static files, while Gzip compresses text before sending it to the browser:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType text/html "access plus 1 day"
</IfModule>
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css text/plain
AddOutputFilterByType DEFLATE application/javascript application/json
</IfModule>
Quick Reference Table of Common Directives
A summary of the main directives and what each one does — use it as a quick lookup when editing the file without re-reading the whole guide:
| Directive | What it does | Module required |
|---|---|---|
RewriteEngine On | Enables all rewrite rules | mod_rewrite |
Redirect 301 | Permanent URL move (SEO friendly) | mod_alias |
RewriteRule | Rewrites or redirects URLs by condition | mod_rewrite |
ErrorDocument | Sets a custom error page | core |
Options -Indexes | Disables directory listing | core |
Require not ip | Blocks an IP (Apache 2.4) | mod_authz_core |
ExpiresByType | Sets cache lifetime per file type | mod_expires |
AddOutputFilterByType DEFLATE | Gzip-compresses output | mod_deflate |
Header set | Adds HTTP headers such as HSTS | mod_headers |
AuthType Basic | Password-protects a folder | mod_auth_basic |
Rule Order and Common Pitfalls
Rules in .htaccess are not applied randomly — they follow a clear order. Understanding it prevents wrong redirects, hangs, and 500 errors.
Rule Order
Apache reads directives top to bottom. For mod_rewrite, a rule ending in [L] (Last) stops processing of the remaining rules immediately. Place specific rules — like a redirect for one page — before broad rules such as forcing HTTPS, so a wide rule doesn't fire first and shadow the more targeted ones.
Watch for Redirect Loops
When you combine forcing HTTPS with www/non-www handling, loose conditions can create an endless redirect loop, leaving the browser stuck on ERR_TOO_MANY_REDIRECTS. Always use a RewriteCond to check the current state before redirecting — for example, test %{HTTPS} off before switching to HTTPS.
Understanding 500 Errors From .htaccess
Most 500 errors come from a syntax mistake, referencing a module the server hasn't enabled, or an unclosed <IfModule> block. Wrapping directives in <IfModule ...> lowers the risk, because Apache simply skips the enclosed lines when the module is missing instead of taking the whole site down.
Caching Gotchas
After changing Expires or cache rules, the site may still show an old version because the browser cached files under the previously set lifetime. Test in an Incognito window or do a hard refresh (Ctrl+F5), and remember that caching frequently updated files for too long will leave users seeing stale content.
Testing .htaccess Safely
Since a single bad line can take down the whole site, use a low-risk testing routine. Follow these steps every time you edit the live file:
- Always back up first — copy .htaccess to
.htaccess.bakin DirectAdmin's File Manager before every edit. - Add one block at a time — add rules group by group and test, rather than pasting several blocks together, so you know which block caused a problem.
- Test multiple URLs — check the homepage, an HTTPS page, the www and non-www forms, and a 404 page to confirm everything behaves as intended.
- Check the error log — if the site returns a 500, the Error Log in DirectAdmin shows the line and reason Apache rejected, helping you find the fault fast.
- Recover instantly if it breaks — rename the file to
.htaccess.offor restore from.htaccess.bakto bring the site back first, then investigate.
If you'd rather not type rules by hand, try the free htaccess Generator below — it builds Redirect, Gzip, Cache, and Security directives in a few clicks.
Important: Always test your site immediately after editing .htaccess. A syntax error will cause an instant HTTP 500 error. If something breaks, comment out the lines you just added with a # prefix to isolate the problem.
Frequently Asked Questions
Where should the .htaccess file be placed?
Place it in the folder where you want the rules to apply — usually public_html. The rules affect that folder and all of its subfolders.
My site shows Error 500 after editing .htaccess — what now?
Error 500 usually means a syntax error or an unsupported directive. Undo your latest change, or temporarily rename the file to confirm .htaccess is the cause. Always back up the original before editing.
Does .htaccess work on every web server?
It works only with Apache — Nginx does not read .htaccess files. AsiaGB hosting uses Apache, so it fully supports .htaccess.
Do .htaccess rules apply instantly or do I need to restart the server?
They apply the moment you save the file — no Apache restart needed, because Apache re-reads .htaccess on every request. That is exactly what makes it convenient on shared hosting, but it also means a mistake affects visitors immediately, so edit carefully.
Does using many .htaccess rules slow the site down?
There is a small cost since Apache reads the file on every request, but for typical sites the difference is barely noticeable. Correct Caching and Gzip rules in the same file usually speed the site up far more than the read cost slows it down, so it is well worth using.
Can I edit .htaccess in DirectAdmin or do I need FTP?
Either works. The File Manager in DirectAdmin is the easiest because you edit and save in the browser — just enable Show Hidden Files to see the file. FTP/SFTP is handy for backing up the file or uploading a version you prepared locally.
Need Hosting with Full .htaccess Support?
AsiaGB Hosting supports Apache mod_rewrite and all .htaccess directives — managed easily through DirectAdmin.
View Hosting Plans