fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← IT & networking

IT & networking / 11 MIN READ

HTACCESS

Modifying .htaccess settings

From the original Fervor library. Examples may use older package versions.

HTACCESS

An .htaccess file (short for hypertext access) is a configuration file used by the Apache web server to manage various aspects of your website at the directory level. These files allow you to enable or disable server features and behaviors by configuring directives. Common uses include:

  • URL rewriting (making URLs shorter or friendlier)
  • Access control (authentication, blocking IP addresses or regions)
  • Redirects (e.g., redirecting old pages to new ones)
  • Changing default index pages
  • Modifying PHP settings (for Apache + PHP setups)
  • Enabling SSI (Server Side Includes)
  • Setting custom error pages

Below is an overview of how .htaccess works and how to get started.


1. How .htaccess Works

  1. Location
    You typically place the .htaccess file in the same directory that you want to configure. The directives in this file apply not only to that directory, but also to all subdirectories beneath it (unless overridden by another .htaccess file deeper in the directory structure).

  2. Processing
    Every time Apache processes an incoming request, it checks for an .htaccess file in the directory being accessed (as well as in any parent directories). It reads the directives in each file and applies them. If you update an .htaccess file, those changes take effect immediately—no Apache restart is required.

  3. Server Settings
    For .htaccess files to work, the Apache AllowOverride directive must be enabled in the server’s main configuration (usually httpd.conf or apache2.conf). If AllowOverride is off or set incorrectly, your .htaccess file might be ignored. For example:

    <Directory /var/www/html>
        AllowOverride All
        Require all granted
    </Directory>
    

    With AllowOverride All, Apache will respect directives in any .htaccess file found within /var/www/html.

  4. Performance Note
    Because Apache checks for (and processes) .htaccess files on every request, it can be less efficient than configuring certain directives directly in the main Apache configuration. For small to medium projects, this overhead is often acceptable, but for larger or high-traffic sites, it can become a performance concern.


2. Common Uses and Examples

A. URL Rewriting (Using mod_rewrite)

URL rewriting is one of the most common tasks handled by .htaccess. You can remove index.php from the URL or create search-engine-friendly URLs. For example:

# Enable rewriting engine
RewriteEngine On

# If the requested file/folder does not exist,
# rewrite to index.php (common in many frameworks)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]

How this works:

  • RewriteEngine On enables the rewriting engine.
  • RewriteCond lines are conditions. They specify that the rewrite should happen only if the requested path does not exist as a file (!-f) or a directory (!-d).
  • RewriteRule ^(.*)$ index.php takes anything (^(.*)$) and sends it to index.php.

B. Basic Redirects

If you need to redirect an old page to a new page, you can use Apache’s redirect directives:

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

Explanation:

  • Redirect 301 indicates a permanent redirect (HTTP status 301).
  • /old-page.html is the path to the old file (relative to your site’s domain).
  • https://example.com/new-page.html is where users should be sent instead.

C. Custom Error Pages

You can override Apache’s default error pages by specifying your own custom pages for HTTP status codes like 404 (Not Found), 403 (Forbidden), etc.:

ErrorDocument 404 /errors/404.html
ErrorDocument 403 /errors/403.html

When a user encounters a “not found” error, they will be shown /errors/404.html instead of the default Apache page.

D. Restricting Access by IP

If you want to block certain IP addresses from viewing your site or specific directories, you can do:

<RequireAll>
    Require all granted
    Require not ip 123.45.67.89
</RequireAll>

This example allows everyone except the IP address 123.45.67.89.

E. Password Protecting a Directory

With a .htaccess file, you can password-protect a folder by referencing an .htpasswd file (a separate file containing usernames and encrypted passwords):

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /var/www/html/.htpasswd
Require valid-user

You’d generate the .htpasswd file using a command-line tool like htpasswd:

htpasswd -c /var/www/html/.htpasswd username

And then follow the prompts to set the user’s password. When users try to access the directory containing the .htaccess file, they will be prompted for a username and password.


3. Best Practices

  1. Backup Before Editing
    Always keep a backup of your current .htaccess file. Mistakes can lead to misconfiguration and downtime.

  2. Use Comments
    Adding comments (using the # symbol) helps you or others understand why certain directives are used:

    # This rule redirects from non-www to www
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]
    
  3. Check Apache Error Logs
    If you see an “Internal Server Error (500)” after changing .htaccess, you may have a syntax error. Check your Apache error logs to see what went wrong.

  4. Consider the Main Server Config
    If your hosting environment allows it (and you have control over httpd.conf), it can be more efficient to place some directives directly in the main server configuration instead of using .htaccess. But in shared hosting, you usually only have access to .htaccess.

  5. Order Matters
    For modules like mod_rewrite, the order of rules can matter. Make sure to place more specific rules earlier (for example, a rule that matches a specific path) and more general rules later.


4. Quick Reference for Common Directives

  • RewriteEngine On|Off
    Enables or disables the URL rewriting engine.

  • RewriteRule
    Defines a rewriting rule. Syntax:

    RewriteRule pattern substitution [flags]
    
  • RewriteCond
    Specifies a condition for the following RewriteRule. Multiple conditions are ANDed together by default.

  • Redirect 301 /old /new
    Creates a permanent (301) redirect from /old to /new.

  • ErrorDocument code /path
    Tells Apache which file to serve for a particular error code.

  • AuthType Basic
    Specifies basic HTTP authentication.

  • AuthUserFile
    Points to the .htpasswd file for storing usernames and passwords.

  • Require all granted / Require valid-user / Require ip
    Controls access by either granting all, requiring a login, or filtering by IP address.


5. Putting It All Together: Sample .htaccess

Here’s a sample .htaccess file combining a few common directives:

# Enable URL rewriting
RewriteEngine On

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

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

# Custom error pages
ErrorDocument 404 /errors/404.html
ErrorDocument 403 /errors/403.html

# Password protect the directory
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /var/www/html/.htpasswd
Require valid-user

Explanation:

  1. RewriteEngine On: Turns on rewriting.
  2. First rewrite rule: if the host is old-domain.com, redirect everything to new-domain.com using a 301 redirect.
  3. Second rewrite rule: if the host starts with www., remove it (rewrite to the domain without www.).
  4. Custom error documents for 404 and 403 errors.
  5. Password protection: sets a basic auth type, references the .htpasswd file, and requires a valid user.

Conclusion

The .htaccess file is a powerful tool for Apache-based websites—especially in shared hosting environments—giving you fine control over redirects, rewrites, password protection, and more without needing full access to the main Apache configuration.

When working with .htaccess, the key points are:

  • Ensure AllowOverride is enabled in your server configuration.
  • Place your .htaccess file in the folder you need to control.
  • Be mindful of syntax and order of directives.
  • Keep an eye on error logs if you run into internal server errors.

With these basics, you’ll be able to accomplish a wide range of server-side customizations and optimizations through .htaccess!

Bonus

Here are some cool or useful things you can do with an .htaccess file, along with when they might be most helpful:


1. Enforce HTTPS

What it does:
If you need to ensure that all traffic goes through a secure (HTTPS) connection, you can force users to always use https:// instead of http://. This enhances security and user trust, especially for e-commerce or login-based websites.

<details> <summary>Example .htaccess snippet</summary>

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

</details>

When it’s useful:

  • Security: Any site handling sensitive data (passwords, personal info, payment info).
  • SEO: Google and other search engines prefer HTTPS.

2. Create Short, User-Friendly URLs

What it does:
Instead of URLs like https://example.com/products.php?id=123, you can have https://example.com/products/123 using Apache’s mod_rewrite. This is not only more user-friendly but also better for SEO.

<details> <summary>Example .htaccess snippet</summary>

RewriteEngine On
# "products/123" -> "products.php?id=123"
RewriteRule ^products/([^/]*)$ products.php?id=$1 [L]

</details>

When it’s useful:

  • SEO: Search engines rank pages higher when URLs contain relevant words.
  • User Experience: Clean URLs are easier to read and remember.

3. Block or Allow Access Based on IP, User Agent, or Referrer

What it does:
You can restrict access to certain files or directories based on IP addresses, user agents (e.g., blocking bots or specific crawlers), or HTTP referrers.

<details> <summary>Example .htaccess snippet</summary>

# Block a specific IP
<RequireAll>
  Require all granted
  Require not ip 123.45.67.89
</RequireAll>

# Alternatively, block based on user agent
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} BadScraper [NC]
RewriteRule .* - [F]

</details>

When it’s useful:

  • Security / Spam Prevention: Block malicious bots or IP addresses.
  • Resource Protection: Prevent known site scrapers or unwanted crawlers from consuming server resources.

4. Set Up Custom Error Pages

What it does:
Serve a friendly, branded 404 (or any other error code) page that helps visitors or guides them back to important areas of your site.

<details> <summary>Example .htaccess snippet</summary>

ErrorDocument 404 /custom_errors/404.html
ErrorDocument 500 /custom_errors/500.html

</details>

When it’s useful:

  • User Experience: A well-designed 404 page can keep visitors engaged even if they land on a broken link.
  • Brand Consistency: Show a page that matches the look and feel of your site, rather than the default server message.

5. Password-Protect an Entire Directory (or Site)

What it does:
Requires users to enter a username and password before accessing a specific folder. This is commonly used for staging sites, sensitive directories, or dev/test environments.

<details> <summary>Example .htaccess snippet</summary>

AuthType Basic
AuthName "Restricted Content"
AuthUserFile /path/to/.htpasswd
Require valid-user

</details>

When it’s useful:

  • Staging/Development: Prevent public access to unfinished or confidential parts of the site.
  • Private Content: Create a simple “members-only” section without needing a full authentication system.

6. Redirect Traffic from One Domain to Another (Domain Aliasing)

What it does:
If you want old-domain.com to point to new-domain.com, you can set up .htaccess rules that automatically redirect visitors.

<details> <summary>Example .htaccess snippet</summary>

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

</details>

When it’s useful:

  • Domain Changes: Rebranding or merging websites.
  • SEO: Preserve SEO “juice” by using 301 (permanent) redirects.

7. Disable Directory Browsing

What it does:
Prevents users from seeing a list of files if there is no index file in a directory.

<details> <summary>Example .htaccess snippet</summary>

Options -Indexes

</details>

When it’s useful:

  • Security: Hides sensitive files or folder structures.
  • User Experience: Prevents a messy list of files from showing up to visitors.

8. Leverage Browser Caching and Compression

What it does:
Speeds up page load times by instructing browsers to cache static files (images, CSS, JS) for a certain period. Also, you can enable Gzip (deflate) compression.

<details> <summary>Example .htaccess snippet</summary>

# Enable Gzip compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css text/javascript application/javascript
</IfModule>

# Leverage browser caching
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType text/css "access plus 1 week"
    # Add more file types as needed
</IfModule>

</details>

When it’s useful:

  • Performance: Reduces load times, critical for user experience and SEO.
  • Bandwidth: You can lower server bandwidth usage.

9. Restrict Hotlinking

What it does:
Prevents other sites from directly linking to your images or files, thus using up your bandwidth without your permission.

<details> <summary>Example .htaccess snippet</summary>

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

</details>

When it’s useful:

  • Resource Management: Prevents third-party sites from using your images or files.
  • Brand Control: Ensures images are used only in approved locations.

10. Advanced Redirect Rules (Based on Language, Browser, Time of Day, etc.)

What it does:
Using RewriteCond, you can get very creative — for example, redirect users based on their language preference, or send specific browsers to tailored versions of a page.

<details> <summary>Example .htaccess snippet</summary>

# Redirect users from Germany (Accept-Language de) to /de/ subfolder
RewriteEngine On
RewriteCond %{HTTP:Accept-Language} ^de [NC]
RewriteRule ^$ de/ [R=302,L]

</details>

When it’s useful:

  • Localization: Automatically direct users to region-specific content.
  • A/B Testing: Show different content for certain user agents or IP ranges.

When .htaccess is Most Useful

  1. Shared Hosting:
    Often you don’t have access to the main Apache configuration files (httpd.conf). .htaccess is typically the only way to customize server behavior on a per-directory basis.

  2. Small to Medium Sites:
    .htaccess allows you to quickly manage redirects, security settings, or rewriting rules without editing the main server config. For larger or high-traffic sites, you might opt for server config changes for performance reasons.

  3. Quick Fixes / Temporary Solutions:
    If you need to create a redirect or block an IP in a hurry, .htaccess changes take effect immediately and don’t require restarting Apache.

  4. Directory-Specific Rules:
    When you only want certain rules to apply to one folder (or set of subdirectories), .htaccess is often easier than editing global configuration files.


Key Takeaways

  • The .htaccess file is a powerful configuration tool that lets you override or extend the main Apache settings on a per-directory basis.
  • You can do everything from rewriting URLs and redirecting traffic to blocking users, enabling security, and speed optimizations.
  • It’s especially handy on shared hosting or when you need fine-grained control for just one part of your site.

By using .htaccess effectively, you can enhance security, performance, SEO, and the overall user experience without needing extensive server-level access!

Keep your curiosity going.Explore more IT & networking →
287 TUTORIALS · 22 TOPICSREADY