The .htaccess file is one of the most useful configuration files for websites running on the Apache HTTP Server. It allows website owners to control specific server behaviors without directly editing the main Apache configuration. From redirecting old URLs to rewriting application routes and restricting access to sensitive files, .htaccess can help manage many common website requirements.
In this .htaccess file explained guide, you will learn how the file works, how to configure rewrite rules and redirects, which security settings are worth considering, and how to troubleshoot common mistakes.
What Is the .htaccess File?
The .htaccess file is a per-directory configuration file supported by Apache HTTP Server. It allows administrators to apply certain configuration directives to a directory and its subdirectories, depending on the server’s configuration.
For example, a website might use .htaccess to:
- Redirect visitors from HTTP to HTTPS.
- Redirect old URLs to new locations.
- Remove unnecessary file extensions from URLs.
- Route application requests through a front controller.
- Restrict access to selected files or directories.
- Set custom error documents.
- Enable browser caching or compression when supported.
The filename begins with a dot, so it may be hidden by default in many file managers and command-line directory listings.
Important: .htaccess is primarily associated with Apache. It does not automatically configure Nginx, and its directives will not work on every hosting environment. Apache must permit the relevant overrides, and the necessary modules must be enabled.
Where Is the .htaccess File Located?
The file is commonly located in a website’s document root, such as public_html on many cPanel hosting accounts.
A typical structure might look like this:
public_html/
├── .htaccess
├── index.php
├── wp-admin/
├── wp-content/
└── wp-includes/
A subdirectory can also contain its own .htaccess file if the server permits it. Configuration rules in a directory can affect requests for that directory and its descendants.
How to Find .htaccess in cPanel
- Log in to your cPanel account.
- Open File Manager.
- Navigate to your website’s document root, commonly
public_html. - Open Settings and enable Show Hidden Files (dotfiles) if the option is available.
- Look for
.htaccessin the directory listing.
If the file is missing, do not immediately assume that something is broken. Some websites do not require a custom .htaccess file, while applications such as WordPress may generate or use one for permalink functionality.
Before editing an existing file, download a copy or create a backup.
How Does .htaccess Work?
When Apache processes a request, it applies the configuration permitted for the requested directory. If .htaccess overrides are enabled, Apache reads applicable files and processes supported directives.
For example, a request for:
https://example.com/old-page
might be redirected to:
https://example.com/new-page
Alternatively, a rewrite rule could internally route /products/123 to a PHP application without changing the URL shown in the visitor’s browser.
These are two different operations:
- Redirect: The server tells the browser to request another URL.
- Rewrite: Apache changes how a request is handled internally, usually without changing the visible URL.
Understanding this distinction is essential when configuring redirects, application routing, and canonical URLs.
Understanding Apache Rewrite Rules
Apache’s mod_rewrite module provides powerful URL manipulation capabilities. The .htaccess directives RewriteEngine, RewriteCond, and RewriteRule are commonly used together.
A basic example is:
RewriteEngine On
RewriteRule ^old-page$ /new-page [R=301,L]
Here’s what each line means:
RewriteEngine Onenables rewrite processing in the applicable context.RewriteRuledefines a pattern and the action to perform when it matches.^old-page$matches the pathold-pagein this per-directory context./new-pageis the destination.R=301sends a permanent redirect.Lstops processing subsequent rewrite rules for the current pass.
In .htaccess context, rewrite patterns generally do not begin with a leading slash because Apache removes the directory prefix before matching them.
Rewrite a URL Without Changing the Browser’s Address
Suppose an application needs to process product URLs through index.php. A simplified example is:
RewriteEngine On
RewriteRule ^products/([0-9]+)/?$ index.php?product_id=$1 [L,QSA]
A request for:
https://example.com/products/123
can be internally rewritten to a request handled by index.php, with product_id=123 available as a query parameter.
The ([0-9]+) expression matches one or more digits, and $1 refers to the first captured group. The QSA flag appends the original query string to the rewritten query string when applicable.
This example illustrates the concept; an actual application must validate incoming parameters and implement appropriate routing and authorization.
How to Redirect HTTP to HTTPS
HTTPS encrypts traffic between a visitor’s browser and the website. If the domain has a valid SSL/TLS certificate and HTTPS is configured correctly, Apache can redirect HTTP requests to HTTPS.
A common .htaccess example is:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
The condition checks whether Apache considers the connection to be using HTTPS. If not, the rule redirects the request to an HTTPS URL while preserving the requested path.
Before using this rule:
- Confirm that the SSL/TLS certificate is valid for the domain.
- Verify that HTTPS works correctly for the website.
- Check whether your hosting provider or application already enforces HTTPS.
- If a reverse proxy or CDN terminates TLS, confirm the correct proxy-aware configuration before relying on
%{HTTPS}. Incorrect handling can cause redirect loops.
Test the rule on a staging website or with a temporary redirect before switching to a permanent 301 redirect.
How to Redirect a Domain or Page
Redirects are useful when moving a website, changing URL structures, consolidating duplicate URLs, or replacing outdated pages.
Redirect One Page to Another
Redirect 301 /old-page https://example.com/new-page
This uses Apache’s mod_alias module rather than mod_rewrite. It permanently redirects requests for the old path to the new destination.
For a straightforward path redirect, Redirect is often simpler than a rewrite rule.
Redirect an Old Domain to a New Domain
If an old domain is being replaced, a possible mod_rewrite configuration is:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^old-example\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.old-example\.com$ [NC]
RewriteRule ^ https://new-example.com%{REQUEST_URI} [R=301,L]
This example redirects requests for either version of old-example.com to the corresponding path on new-example.com.
Before deploying it, adjust the domain names and confirm that the new destination is correct. If the old domain also serves other subdomains, make sure the rule does not unintentionally affect them.
301 vs. 302 Redirects
Choose the redirect status according to your actual intention.
| Status | Meaning | Typical use |
|---|---|---|
| 301 | Moved Permanently | Permanent page or domain migration |
| 302 | Found; temporary redirect | Temporary destination |
| 307 | Temporary Redirect | Temporary redirect that preserves the request method |
| 308 | Permanent Redirect | Permanent redirect that preserves the request method |
For ordinary page migrations, 301 is widely used. For temporary changes, choose a temporary status. Method preservation can matter for POST requests and API endpoints, so do not treat every redirect status as interchangeable.
How to Remove .php from URLs
Some PHP websites prefer URLs such as /about instead of /about.php. A simple internal rewrite can support this pattern:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)/?$ $1.php [L]
This rule attempts to map a URL to a corresponding PHP file when the requested path is neither an existing directory nor an existing file.
For example, /about may be internally mapped to about.php.
However, this does not automatically redirect /about.php to /about, and it does not guarantee that every route is valid. If you want clean, canonical URLs, configure the internal rewrite and any required external redirect separately. Ensure that the application handles missing files and access permissions correctly.
For frameworks and content management systems, use the routing rules recommended by the application instead of adding generic rules without testing them.
How WordPress Uses .htaccess
WordPress installations running on Apache commonly use .htaccess to support pretty permalinks.
A standard WordPress block often resembles this:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
The rules allow requests that do not correspond to existing files or directories to be handled by WordPress’s front controller, index.php.
The authorization-header rule may be included to preserve the Authorization header for applications or plugins that need it.
Important: WordPress may manage the contents between its marker comments. Avoid replacing this block with unrelated rules, and keep custom configuration outside the managed section where possible.
If WordPress pages return 404 errors after changing permalink settings, check whether the rules exist, whether Apache permits the required overrides, and whether mod_rewrite is available.
Security Considerations for .htaccess
The .htaccess file can contribute to website security, but it is not a complete security solution. Application-level authorization, secure coding, correct file permissions, and server-level protections remain essential.
1. Restrict Access to Sensitive Files
For Apache configurations that support the following authorization syntax, you can restrict access to a specific file:
<Files "config.php">
Require all denied
</Files>
This denies HTTP access to config.php in the applicable directory context. Use it only when the file should never be served directly to visitors.
Apache 2.4 uses Require directives for authorization. Older Apache versions may use different syntax, so check the server version and configuration before applying examples from older tutorials.
2. Disable Directory Listings
If directory indexing is enabled, visitors might be able to view a directory’s contents when no index document is present.
You can disable directory listings with:
Options -Indexes
This prevents Apache’s automatic directory listing from being displayed in the applicable context, assuming the hosting configuration permits the directive.
It does not prevent access to files whose names are already known or discoverable. Sensitive files should not be placed in publicly accessible directories merely because indexing is disabled.
3. Avoid Exposing Backup and Configuration Files
Backup archives, database dumps, environment files, and temporary copies can expose sensitive information if stored under the public document root.
The safest approach is to keep private files outside the web root whenever possible. If that is not possible, configure access restrictions and verify them with direct HTTP requests.
For example, you might restrict access to a specific file:
<Files ".env">
Require all denied
</Files>
This is only a supplementary safeguard. It does not replace proper secret management, and it should not be assumed to protect every similarly named file in every directory.
4. Be Careful With IP-Based Restrictions
Access can be restricted to selected IP addresses when a resource is intended for a limited audience:
<RequireAll>
Require all denied
Require ip 203.0.113.10
</RequireAll>
Replace the example IP address with the actual authorized address. The example IP belongs to a documentation range and should not be used as a real client address.
Incorrect IP restrictions can lock you out of an administrative page or block legitimate users. Behind a proxy or CDN, Apache may see the proxy’s IP rather than the visitor’s IP unless trusted client-IP handling is configured correctly.
5. Do Not Copy Security Rules Blindly
A rule that works on one Apache server may fail on another because of differences in modules, permissions, server versions, or hosting restrictions.
Review every rule before deployment. Test that authorized visitors can still access required resources and that unauthorized requests are actually denied.
Common .htaccess Errors and How to Fix Them
A small configuration mistake can affect every page under a directory. The following issues are among the most common.
500 Internal Server Error
A malformed directive, unsupported option, invalid rewrite rule, or prohibited override can trigger an HTTP 500 response.
How to troubleshoot:
- Restore the previous working
.htaccessfile or temporarily rename the modified file to test whether it is responsible. - Review the Apache error log or the hosting control panel’s error interface.
- Check for misspelled directives and invalid syntax.
- Confirm that the required modules and overrides are available.
- Reintroduce changes one at a time.
Do not leave a production website without required routing or access protections while troubleshooting.
Redirect Loop
A redirect loop occurs when a request repeatedly redirects between URLs or back to itself.
Common causes include:
- Conflicting HTTP-to-HTTPS rules.
- Duplicate redirects in
.htaccess, the application, and a CDN. - Incorrect HTTPS detection behind a reverse proxy.
- Conflicting
wwwand non-wwwcanonicalization rules.
Inspect the complete redirect chain and identify which layer is issuing each redirect. Keep one consistent canonical URL policy and configure proxy-aware HTTPS detection when required.
Rewrite Rules Do Not Work
If rewrite rules appear to be ignored, verify that:
- Apache’s
mod_rewritemodule is enabled. - The relevant
.htaccessfile is in the correct directory. - The server allows the required directives through its override configuration.
- The pattern matches the requested path in the current directory context.
- Another rule is not intercepting the request first.
On shared hosting, you may not have permission to change the main Apache configuration. Contact your hosting provider if the problem requires server-level changes.
Website Returns 404 Errors
A rewrite rule may point to a nonexistent destination, or a CMS may no longer have the routing rules it expects.
Check the requested URL, confirm that the destination file or application route exists, and review any recent permalink or deployment changes.
Changes Do Not Appear Immediately
Unlike some browser-side settings, .htaccess changes are normally read by Apache during request processing rather than being stored in a typical browser cache. However, browser caching, CDN behavior, application caching, and permanent redirects can make testing confusing.
Use a private browsing window or a command-line HTTP client to inspect the response. When testing a new redirect, start with a temporary status code and switch to a permanent redirect only after confirming the destination.
How to Test .htaccess Changes With curl
The curl command can help inspect HTTP response headers and redirect behavior.
To check a page’s response headers:
curl -I https://example.com/
To display the redirect chain:
curl -IL http://example.com/old-page
The -I option requests headers, while -L tells curl to follow redirects. Review the HTTP status codes and Location headers to determine where requests are being sent.
These commands help diagnose redirect behavior, but they do not validate every .htaccess directive or prove that security rules are effective. Test the actual resource and relevant access scenarios as well.
Best Practices for Managing .htaccess
Follow these practices to reduce configuration problems:
- Back up before editing. Save the last known working file so you can restore it quickly.
- Make small changes. Add one rule at a time and test after each change.
- Avoid duplicate rules. Multiple redirects for the same URL can cause loops or unnecessary hops.
- Use the correct modules. Confirm that the server supports each directive you use.
- Preserve application-managed sections. WordPress and other applications may regenerate their rewrite blocks.
- Keep sensitive files outside the web root. Access restrictions should be a secondary layer, not your only protection.
- Use temporary redirects during testing. Switch to permanent redirects only after confirming the behavior.
- Review logs when errors occur. Apache error logs often provide the clearest explanation of a configuration failure.
- Document custom rules. Comments make it easier to understand why each rule exists.
- Test the final configuration. Check normal pages, redirects, missing URLs, and restricted resources.
Does .htaccess Affect Website Performance?
Because Apache may need to check applicable .htaccess files during request processing, excessive per-directory configuration can add overhead. The impact depends on the server, directory structure, rules, and traffic.
For small websites, a modest set of well-written rules is usually manageable. Large or high-traffic deployments may benefit from moving suitable directives into the main Apache configuration, where an administrator can configure them more efficiently.
On shared hosting, however, the main Apache configuration is typically controlled by the hosting provider. Avoid adding complex rules unless they solve a specific requirement.
When Should You Use .htaccess?
The .htaccess file is useful when you need directory-level Apache configuration and do not have access to the main server configuration.
Typical use cases include:
- Redirecting old URLs.
- Enforcing a canonical URL structure.
- Supporting CMS permalinks.
- Restricting access to selected files.
- Disabling automatic directory listings.
- Defining custom error documents.
- Applying other supported per-directory directives.
For server-wide settings, advanced security controls, or large collections of rewrite rules, the main Apache configuration may be more appropriate when you have administrative access.
If your website runs on Nginx without Apache, .htaccess rules will not be applied. Equivalent behavior must be configured in Nginx’s server configuration.
Final Thoughts
Understanding the .htaccess file gives website owners more control over URL handling, redirects, and selected access restrictions on Apache-powered websites. Correctly configured rules can support clean URLs, website migrations, CMS routing, and additional security measures.
The key is to make deliberate changes, understand the difference between rewrites and redirects, and test every rule before deploying it to a live website. When a configuration produces an unexpected result, review the error logs and isolate the latest change instead of adding more rules blindly.
With careful configuration and regular testing, .htaccess can remain a useful part of your website administration toolkit.
