Skip to main content

Working with .htaccess Files

1. Understanding .htaccess Purpose and Use Cases

Use Case Description Example
URL Rewriting Modify URLs dynamically for cleaner routing or redirects
RewriteEngine On
RewriteRule ^old-page$ /new-page [R=301,L]
Access Control Restrict access to directories or files based on IP or user Require ip 192.168.1.0/24
Custom Error Pages Define custom pages for HTTP error codes like 404 or 500 ErrorDocument 404 /custom-404.html
MIME Type Handling Set content types for specific file extensions AddType application/json .json
Security Headers Add security headers like CSP or HSTS to responses Header set X-Content-Type-Options "nosniff"
Compression Enable Gzip compression for better performance
LoadModule deflate_module modules/mod_deflate.so
AddOutputFilterByType DEFLATE text/html
Note: .htaccess files are processed for every request, which can impact performance. Use them sparingly and consider placing rules in the main server config when possible.

2. Enabling .htaccess Support

Directive Description Default Notes
AllowOverride Controls which directives can be overridden in .htaccess files None Must be set in main server config or virtual host
AccessFileName Name of the file to look for in each directory .htaccess Can be changed to another filename

Example: Enabling .htaccess Support

<Directory "/var/www">
    AllowOverride All
</Directory>
Note: AllowOverride must be set to All or specific directives to enable .htaccess files.

3. Creating .htaccess Files

Use the following steps to create and configure .htaccess files for your Apache HTTP Server:

Workflow: Creating an .htaccess File

  1. Create a new file named .htaccess in the directory where you want to apply the rules.
  2. Add configuration directives to the file using valid Apache syntax.
  3. Ensure the file is readable by the web server process (e.g., chmod 644).
  4. Restart or reload the Apache server to apply changes (if necessary).
Directive Description Example
RewriteEngine Enables or disables the rewrite engine. RewriteEngine On
RewriteRule Defines rewrite rules for URL rewriting. RewriteRule ^old\.html$ new.html [R=301,L]
Redirect Performs a redirect from one URL to another. Redirect 301 /old-page.html /new-page.html
ErrorDocument Customizes error pages for specific HTTP status codes. ErrorDocument 404 /custom-404.html

Example: Basic .htaccess Configuration

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^old\.html$ new.html [R=301,L]
</IfModule>

ErrorDocument 404 /custom-404.html
Note: The .htaccess file must be placed in the directory where it should apply, and Apache must have AllowOverride enabled for the directory to allow overrides.

4. Setting DirectoryIndex in .htaccess

Directive Values Description
DirectoryIndex index.html Specifies the default file to serve when a directory is requested

Example: Setting DirectoryIndex

DirectoryIndex index.html

Example: Setting Multiple Index Files

DirectoryIndex index.html index.php
Note: The server will check for files in the order listed and serve the first one found.

5. Configuring Custom Error Pages

Error Code Default Message Custom Page Location Notes
400 Bad Request ErrorDocument 400 /errors/bad-request.html Used for malformed requests
401 Unauthorized ErrorDocument 401 /errors/unauthorized.html For protected resources without valid credentials
403 Forbidden ErrorDocument 403 /errors/forbidden.html Access denied due to permissions or directory listing disabled
404 Not Found ErrorDocument 404 /errors/not-found.html Most common custom error page
500 Internal Server Error ErrorDocument 500 /errors/server-error.html Generic server-side error page
503 Service Unavailable ErrorDocument 503 /errors/service-unavailable.html Used during maintenance or overload

Example: Setting up a custom 404 page

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /errors/not-found.html [L]
</IfModule>
Note: The ErrorDocument directive can reference local files or remote URLs.
Warning: Avoid using complex HTML or JavaScript in error pages as they may not render correctly.

6. Implementing Redirects

Directive Parameters Description Example
Redirect permanent, temp, found, moved Performs a redirect with specified status code Redirect permanent /old-page.html /new-page.html
RedirectMatch Regex pattern, target URL Redirects based on a regex match RedirectMatch permanent ^/old/(.*)$ /new/$1
RedirectTemp Source URL, Target URL Temporary redirect (302) RedirectTemp /temp.html /permanent.html

Example: Redirecting a Directory

Redirect permanent /old-directory/ /new-directory/

Example: Redirect with Regex

RedirectMatch permanent ^/products/([0-9]+)/$ /item/$1/
Note: Use Redirect permanent for SEO-friendly 301 redirects.
Warning: Avoid infinite redirect loops by ensuring the target URL does not match the source pattern.

7. Using Rewrite Rules

Rule Description Example
RewriteEngine On Enables the rewrite engine RewriteEngine On
RewriteRule Defines a rewrite rule pattern RewriteRule ^old-page\.html$ /new-page.html [R=301,L]
RewriteCond Applies conditions to rewrite rules RewriteCond %{HTTPS} off<br>RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Example: Redirecting HTTP to HTTPS

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

Example: Redirecting Old URLs to New

RewriteEngine On
RewriteRule ^old-page\.html$ /new-page.html [R=301,L]
Note: The [R=301,L] flags indicate a permanent redirect and that this is the last rule to process.
Warning: Misconfigured rewrite rules can cause infinite loops or server errors. Always test in a development environment.

8. Setting MIME Types

MIME Type File Extension Description Example
text/html .html, .htm HTML documents <html><head><title>Hello</title></head>
text/css .css Cascading Style Sheets body { color: red; }
application/javascript .js JavaScript files console.log('Hello');
image/jpeg .jpg, .jpeg JPEG images <img src="photo.jpg">
image/png .png PNG images <img src="logo.png">
application/json .json JSON data {"name": "John"}
text/plain .txt Plain text files Hello, world!
application/pdf .pdf Portable Document Format <embed src="document.pdf">

Example: Setting MIME Type in .htaccess

AddType text/html .html
AddType application/json .json

9. Configuring Authentication in .htaccess

Directive Description Example
AuthType Sets the authentication method to use AuthType Basic
AuthName Defines the realm name for authentication AuthName "Restricted Area"
AuthUserFile Specifies the path to the file containing user credentials AuthUserFile /path/to/.htpasswd
Require Defines which users or groups are allowed access Require valid-user

Example: Basic Authentication Setup

# Create the .htpasswd file with a user
htpasswd -c /path/to/.htpasswd john

# Add another user
htpasswd /path/to/.htpasswd jane

Example: .htaccess Configuration

<Directory "/var/www/protected">
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /var/www/.htpasswd
    Require valid-user
</Directory>
Note: The .htpasswd file should be placed outside the web root to prevent direct access.
Warning: Basic authentication sends credentials in base64 encoding, which is not secure over HTTP. Always use HTTPS.

10. Setting Custom Headers

Directive Description Values Notes
Header set Sets a custom header field name value Can be used to set any custom header
Header unset Removes a header field name Useful for removing default headers
Header append Adds a header field if it doesn't exist name value Appends to existing headers with same name

Example: Setting a Custom Header

Header set X-Custom-Header "MyValue"

Example: Removing a Default Header

Header unset X-Powered-By
Note: Headers set in .htaccess are applied to all requests handled by the directory and its subdirectories.

11. Understanding Performance Impact

Directive Description Performance Impact Notes
RewriteEngine Enables or disables the rewrite engine Medium Can slow down request processing if many rules are present
RewriteRule Defines rewrite rules for URL manipulation High Each rule is evaluated per request; complex regex can be CPU-intensive
RewriteCond Applies conditions to rewrite rules Medium Adds overhead to rule evaluation but is necessary for conditional rewrites
FilesMatch Applies directives to files matching a pattern Medium Can slow down file access if patterns are complex or numerous
DirectoryIndex Specifies default file for directory requests Low Minimal impact; cached by server
ExpiresByType Sets expiration headers for content types Low Minimal overhead; improves caching efficiency
Note: The performance impact of .htaccess files is primarily due to the file being read and parsed on every request, which can be avoided by placing directives in the main server config.

12. Disabling .htaccess

Directive Description Default Notes
AllowOverride Controls whether .htaccess files are allowed to override server configuration None Set to None to disable .htaccess entirely

Example: Disabling .htaccess

<Directory "/var/www">
    AllowOverride None
</Directory>
Note: Setting AllowOverride to None prevents any .htaccess files from being processed, effectively disabling their functionality.

Was this article helpful?