| |

Complete .htaccess Guide: Rewrite Rules & Security Directives

Complete .htaccess Guide: Rewrite Rules & Security Directives

Verified Answer

An Apache .htaccess file applies directory-level server rules without restarting Apache. On Linux hosting, it manages mod_rewrite URL routing, 301 canonical redirects, Apache 2.4 Require IP controls, Options -Indexes directory protection, and browser cache headers—though high-traffic sites benefit from moving rules into vhost configs.

A single misplaced regex inside .htaccess can trigger site-wide 500 errors or infinite redirect loops. Use this practical .htaccess guide for clean mod_rewrite rules, 301 canonical redirects, Apache 2.4 IP restrictions, and browser caching.

Clean URL Routing

Master RewriteCond, RewriteRule, and [L,R=301] flags for canonical www, HTTPS, and slug redirects.

Apache 2.4 Security Syntax

Replace deprecated 2.2 Deny from rules with modern Require all denied and FilesMatch blocks.

Zero-Downtime Editing

Edit safely over SSH, SFTP, or cPanel File Manager while avoiding common 500 Internal Server Error syntax traps.

How .htaccess Works Inside the Apache Request Pipeline

When a visitor requests https://example.com/blog/linux-guide/, Apache walks the filesystem path from the document root down to the target directory, checking for a .htaccess file at every level whenever AllowOverride is enabled in the virtual host configuration. Directives in a deeper subdirectory override directives in parent directories.

This flexibility comes with an important operational rule: only use .htaccess when you do not control the main Apache virtual host file, or when your hosting control panel isolates each tenant inside /home/username/public_html. On dedicated VPS setups where you own root access, placing static rewrite rules inside <VirtualHost> with AllowOverride None eliminates per-request directory stat calls. On shared and managed Linux hosting, however, .htaccess remains the standard, instant-reload control plane.

How to View and Edit .htaccess Safely on Linux Hosting

Because filenames starting with a period are hidden by default in Unix/Linux shells and FTP clients, beginners often assume their site has no .htaccess file and accidentally overwrite an existing one. Always check with hidden files revealed before creating a new file:

Terminal / CLI
# Via SSH: list all hidden files and back up .htaccess
cd ~/public_html
ls -la
cp .htaccess .htaccess.bak.$(date +%F)

If you use cPanel File Manager instead of SSH, click Settings in the top-right corner and check Show Hidden Files (dotfiles). Always edit with a plain-text editor (such as nano, vim, or VS Code over SFTP) using LF (Unix) line endings—never Microsoft Word or rich-text editors that insert smart quotes or CRLF byte sequences.

Anatomy of mod_rewrite: RewriteCond, RewriteRule, and Flags

Most .htaccess rules rely on Apache’s mod_rewrite engine. Understanding its three building blocks prevents endless trial-and-error:

  • RewriteEngine On: Activates the rewrite engine for the current directory scope. You only need this line once at the top of your rewrite block.
  • RewriteCond TestString CondPattern [Flags]: Defines a condition that must evaluate to true before the very next RewriteRule runs. Multiple RewriteCond lines stack with an implicit logical AND unless you append [OR].
  • RewriteRule Pattern Substitution [Flags]: Matches the requested URL path (without the leading slash in .htaccess) against a regular expression and rewrites or redirects it.

The bracketed flags at the end of a rule control execution flow:

Flag Meaning Production Usage
[L] Last rule Stops processing further rules in the current pass once matched.
[R=301] Permanent HTTP Redirect Instructs browsers and search engines to update bookmarks and index URLs.
[NC] No Case Makes regex pattern matching case-insensitive (useful for domain/file extensions).
[QSA] Query String Append Preserves existing URL parameters (like ?utm_source=...) during internal rewrites.
[END] Terminate All Passes Halts rewriting completely, preventing internal sub-request loops in Apache 2.4.

Essential 301 Redirect Recipes for SEO and Canonicalization

When you rename a page, retire an old directory, or consolidate duplicate URLs, permanent 301 redirects preserve search equity and prevent 404 errors. Always place specific page-to-page redirects above generic CMS catch-all rules.

Terminal / CLI
<IfModule mod_rewrite.c>
  RewriteEngine On

  # Single URL 301 redirect (simple mod_alias alternative)
  Redirect 301 /old-hosting-page/ https://yourdomain.com/linux-web-hosting/

  # Redirect an entire legacy directory to a new path
  RewriteRule ^old-blog/(.*)$ /guides/$1 [R=301,L]

  # Strip .html extensions cleanly
  RewriteCond %{THE_REQUEST} \s/+(.+?)\.html[\s?] [NC]
  RewriteRule ^ /%1 [R=301,NE,L]
</IfModule>

Forcing HTTPS and Canonical www / non-www Domains

Combine HTTPS enforcement and hostname canonicalization into a single 301 hop whenever possible. Doing it in two separate rules forces mobile browsers through two sequential redirects (for example, http://www → https://www → https://non-www), adding unnecessary TLS latency. For deeper TLS header hardening such as HSTS and CSP, see our dedicated guide to enforcing HTTPS and security headers via .htaccess.

Terminal / CLI
<IfModule mod_rewrite.c>
  RewriteEngine On

  # Force HTTPS AND non-www in a single 301 hop
  RewriteCond %{HTTPS} off [OR]
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ https://yourdomain.com%{REQUEST_URI} [R=301,L,NE]
</IfModule>

If your site sits behind a reverse proxy or Cloudflare Flexible/Full SSL that terminates TLS before reaching Apache, replace %{HTTPS} off with RewriteCond %{HTTP:X-Forwarded-Proto} !https to prevent infinite redirect loops.

WordPress and Laravel Front-Controller Rewrite Rules

Modern PHP frameworks and CMS platforms route all non-file URLs through a single index.php front controller. Keep this block at the bottom of your .htaccess file so your 301 redirects and security blocks evaluate first:

Terminal / CLI
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.php$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.php [L]
</IfModule>

The two conditions !-f (not an existing file) and !-d (not an existing directory) ensure Apache serves real images, CSS, and JavaScript directly without invoking PHP.

Server-Level Security Directives in .htaccess

While .htaccess is not a replacement for a kernel firewall or ModSecurity WAF and Fail2ban protection, it acts as a fast first line of defense against automated scanners, directory snooping, and credential harvesting.

Blocking IP Addresses and Bad Bots (Apache 2.4 Require Syntax)

Most Linux servers today run Apache 2.4, which deprecated the old Apache 2.2 Order Allow,Deny / Deny from syntax. Using mod_authz_core‘s <RequireAll> block is cleaner and avoids compatibility errors when mod_access_compat is disabled:

Terminal / CLI
# Block specific abusive IPv4/IPv6 addresses or CIDR ranges (Apache 2.4)
<RequireAll>
  Require all granted
  Require not ip 198.51.100.42
  Require not ip 203.0.113.0/24
</RequireAll>

# Block aggressive scraper user-agents via mod_rewrite
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_USER_AGENT} (MJ12bot|DotBot|BLEXBot|SemrushBot) [NC]
  RewriteRule .* - [F,L]
</IfModule>

The [F,L] flag returns an immediate 403 Forbidden response before PHP or MySQL ever spin up.

Disabling Directory Browsing and Protecting Config Files

If a directory inside public_html lacks an index.html or index.php file, Apache’s default Indexes option may list every file inside it to anyone on the internet. Disable directory browsing globally and lock down configuration files, Git metadata, and environment files in one block:

Terminal / CLI
# Disable directory listings
Options -Indexes

# Block direct HTTP access to sensitive dotfiles, backups, and config files
<FilesMatch "^\.(env|git|htaccess|htpasswd|user\.ini)$|^(wp-config\.php|composer\.(json|lock)|readme\.html)$">
  Require all denied
</FilesMatch>

# Prevent PHP execution inside upload directories (place in wp-content/uploads/.htaccess)
<FilesMatch "\.(php|phtml|php[0-9])$">
  Require all denied
</FilesMatch>

Denying PHP execution inside writable upload directories is one of the simplest, highest-impact hardening steps on Linux hosting: even if an attacker uploads a disguised script, Apache refuses to execute it.

Browser Caching and Compression Directives (mod_expires & mod_deflate)

Beyond routing and security, .htaccess lets you instruct browsers to cache static assets locally and accept Gzip-compressed text payloads. Always wrap these directives in <IfModule> checks so Apache never crashes if a module is disabled on a specific server:

Terminal / CLI
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css
  AddOutputFilterByType DEFLATE application/javascript application/json image/svg+xml
</IfModule>

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

Notice text/html "access plus 0 seconds": you want browsers caching versioned CSS, JS, and images for a full year, while keeping HTML dynamic so logged-in sessions and fresh content updates appear immediately. For server-side PHP acceleration, pair these headers with OPcache and FastCGI caching.

Common .htaccess Mistakes That Cause 500 Internal Server Errors

Because Apache parses .htaccess live on every request, a single syntax error immediately turns your entire website into a blank 500 Internal Server Error. Understanding the exact failure patterns saves minutes of downtime when deploying new rules:

  • Unwrapped Module Directives: Using ExpiresActive On or Header set outside an <IfModule> block when that Apache module (such as mod_expires or mod_headers) is not loaded on the server.
  • Using php_value or php_flag Under PHP-FPM: Those directives only work with mod_php. On modern MultiPHP / PHP-FPM hosting, move PHP overrides to .user.ini or php.ini.
  • Infinite Rewrite Loops: Redirecting to a URL that still matches the same RewriteCond (exceeding Apache’s LimitInternalRecursion of 10 passes), which floods error_log with Request exceeded the limit of 10 internal redirects.
  • Disallowed Options Flags: Using Options +FollowSymLinks on shared hosts where AllowOverride only permits SymLinksIfOwnerMatch. Swapping to Options +SymLinksIfOwnerMatch resolves the crash immediately without weakening symlink security.
  • Windows CRLF Line Endings or BOM Characters: Uploading an .htaccess saved with a UTF-8 Byte Order Mark (BOM) or Windows \r\n line endings can cause Apache to reject the very first directive on line 1. Strip hidden characters via SSH with sed -i 's/\r$//' .htaccess.

If a rule edit triggers an immediate crash, restore your .htaccess.bak copy and inspect the exact line number in Apache’s error log using our 500 Internal Server Error log diagnostics guide. When testing complex regex redirects, test against a staging subdomain first or validate individual paths with curl -sI https://yourdomain.com/old-path so you verify the exact 301 Moved Permanently and Location: headers before search engines crawl the change.

Frequently Asked Questions

Why is my .htaccess file not working on Linux hosting?

First, confirm the filename is spelled exactly .htaccess (with the leading dot and no .txt extension) and resides in the document root (public_html). Second, check file permissions (chmod 644 .htaccess). If it still has no effect, your Apache virtual host may have AllowOverride None set, or your server may be running Nginx directly—Nginx does not read .htaccess files.

Do I need to restart Apache after editing .htaccess?

No. Apache reads .htaccess dynamically on every request, so changes take effect the instant you save the file. This is why it is essential to back up the file before editing and test a page load immediately afterward.

Can I put php_value memory_limit in .htaccess on PHP-FPM?

No. php_value and php_flag are Apache mod_php directives and will cause a 500 Internal Server Error on PHP-FPM or CGI/FastCGI servers. Instead, place memory_limit = 256M inside a .user.ini file in your document root or configure it via cPanel MultiPHP INI Editor.

Should 301 redirects go before or after WordPress rewrite rules?

Always place custom 301 redirects above the # BEGIN WordPress block. If you place them below, WordPress’s RewriteRule . /index.php [L] catch-all rule intercepts the request first and your 301 redirect may never execute.

What is the difference between Redirect 301 and RewriteRule [R=301,L]?

Redirect 301 belongs to mod_alias and is ideal for simple static path-to-URL redirects. RewriteRule belongs to mod_rewrite and is required whenever you need conditional logic (such as checking %{HTTPS}, %{HTTP_HOST}, query strings, or regular expression captures).

Does .htaccess slow down my Linux website?

A clean, concise .htaccess file adds negligible overhead (fractions of a millisecond) on NVMe SSD hosting. Performance degradation only happens if you accumulate hundreds of unanchored regex redirects or place .htaccess files inside dozens of nested subdirectories.

Apply Clean .htaccess Routing Without Slowing Request Latency

Well-structured mod_rewrite redirects, IP allowlists, and browser cache headers protect your site without triggering 500 errors. Host your Apache workloads on fast NVMe storage that parses directory rules effortlessly.

Host Apache workloads on NVMe Linux plans