StarDomain

Introduction to .htaccess Files

Introduction to .htaccess Files

The .htaccess file is one of the most powerful configuration tools available on Apache-based web hosting. It allows you to control how your web server handles requests, manage redirects, set security policies, and much more — all without needing root access to the server. This guide provides a comprehensive introduction to .htaccess files and their most common uses.

What Is an .htaccess File?

An .htaccess (Hypertext Access) file is a directory-level configuration file for the Apache web server. Key characteristics:

  1. Plain text file named exactly .htaccess (note the leading dot)
  2. Placed in any directory within your web space
  3. Affects the directory it is in and all subdirectories below it
  4. Processed on every request — changes take effect immediately (no server restart needed)
  5. Overrides server configuration for the directory scope

Tip: The leading dot in the filename makes it a hidden file on Linux/macOS systems. Use ls -la in your terminal or enable "Show Hidden Files" in your file manager to see it.

Creating an .htaccess File

Using cPanel File Manager

  1. Log in to cPanel
  2. Open File Manager
  3. Navigate to the directory where you want the .htaccess file (usually public_html)
  4. Click Settings (top right) and check Show Hidden Files (dotfiles)
  5. If no .htaccess exists, click + File and name it .htaccess
  6. Right-click the file and select Edit to modify it

Using DirectAdmin File Manager

  1. Log in to DirectAdmin
  2. Go to System Info & Files > File Manager
  3. Navigate to your domains/example.com/public_html directory
  4. Create or edit the .htaccess file

Using FTP/SFTP

  1. Connect to your server using an FTP client (FileZilla, WinSCP, etc.)
  2. Navigate to the directory where you want the file
  3. Create a new file named .htaccess on your local machine
  4. Upload it to the server
  5. Ensure the file has permissions set to 644

Important: Always create a backup of your existing .htaccess file before making changes. A single syntax error can make your entire site return a 500 Internal Server Error.

Essential .htaccess Directives

1. Custom Error Pages

Display custom pages when errors occur:

ErrorDocument 404 /errors/notfound.html
ErrorDocument 403 /errors/forbidden.html
ErrorDocument 500 /errors/servererror.html

This improves user experience by showing a helpful page instead of a generic server error.

2. HTTPS Redirect

Force all visitors to use the secure HTTPS version of your site:

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

3. WWW Redirect

Redirect non-www to www (or vice versa) for consistent URLs:

Non-www to www:

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

WWW to non-www:

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

4. Directory Index

Specify which file to load as the default page:

DirectoryIndex index.html index.php index.htm

Apache will serve the first file it finds in the order listed.

5. Directory Listing Prevention

Prevent visitors from browsing your directory contents:

Options -Indexes

Without this, if no index file exists in a directory, Apache will show a listing of all files — a security risk.

6. File Access Protection

Block access to specific files:

<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|sql)$">
  Order Allow,Deny
  Deny from all
</FilesMatch>

7. Password Protection

Protect a directory with a username and password:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/username/.htpasswd
Require valid-user

You must also create the .htpasswd file with encrypted passwords (use cPanel's Directory Privacy tool or the htpasswd command).

8. PHP Configuration

Adjust PHP settings for your hosting environment:

php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300
php_value memory_limit 256M

Note: PHP configuration via .htaccess works with mod_php. If your server uses PHP-FPM or CGI/FastCGI, use a .user.ini file or php.ini instead.

9. MIME Types

Define how the server handles specific file types:

AddType application/pdf .pdf
AddType audio/mpeg .mp3
AddType video/mp4 .mp4
AddType application/font-woff2 .woff2

10. Caching Headers

Improve site performance with browser caching:

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType application/javascript "access plus 1 month"
</IfModule>

.htaccess File Scope and Inheritance

Understanding scope is critical:

  • An .htaccess in public_html/ affects your entire website
  • An .htaccess in public_html/blog/ affects only the /blog/ directory and its subdirectories
  • Child .htaccess files inherit settings from parent directories
  • Child .htaccess files can override parent settings

Common Mistakes to Avoid

  1. Syntax errors: A single typo causes a 500 error for your entire site. Always keep a backup.
  2. Infinite redirect loops: Be careful with redirect rules — test them thoroughly.
  3. Wrong file permissions: .htaccess should be 644 (readable by the server but not writable by others).
  4. Missing RewriteEngine On: Rewrite rules will not work without this directive.
  5. Order of rules matters: Rules are processed top-to-bottom. Place more specific rules before general ones.
  6. Excessive .htaccess files: Having too many nested .htaccess files can slow down your server. Consolidate where possible.

Debugging .htaccess Issues

When something goes wrong:

  1. Check error logs: Review your Apache error log in cPanel (Metrics > Errors) for specific error messages
  2. Comment out rules: Add a # before lines to disable them one at a time
  3. Start simple: Begin with minimal rules and add complexity gradually
  4. Test in a subdirectory: Create a test .htaccess in a subdirectory first
  5. Verify mod_rewrite is enabled: Most shared hosting environments have it enabled, but verify if rewrite rules are not working
  • Common .htaccess URL Rewrite Rules
  • How to Force HTTPS on Your Website
  • Troubleshooting 500 Internal Server Errors

If you need help with .htaccess configuration, contact our support team at {{SUPPORT_EMAIL}} or visit {{SUPPORT_URL}}. We can help you set up redirects, security rules, and performance optimizations.