.htaccess is a plain-text configuration file for the Apache web server. It applies settings to the directory it sits in and everything below it, such as redirects, rewrite rules, HTTP headers and access restrictions. Changes take effect without a server restart.
How does .htaccess work?
Apache looks for a file named .htaccess in the requested directory and in each parent directory. This only happens if the server setting AllowOverride permits it. Its default value is None, which means the files are ignored until an administrator enables them.
The Apache project advises putting settings in the main server configuration whenever you have access to it. Reading .htaccess files on every request costs performance, and the files are meant for cases where people can change settings per directory without root access, which is common on shared hosting and in CMS setups.
For SEO, the file is mostly used for redirects, forcing HTTPS and sending headers such as X-Robots-Tag. WordPress also writes its permalink rules into it.
According to reports, nginx does not read .htaccess. The same rules have to go into the nginx configuration.
Example
# Permanent redirect of a single URL
Redirect 301 /old-page https://example.com/new-page
# Redirect all HTTP requests to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Common mistakes
- According to reports, a syntax error can make the server return a 500 error for every page in that directory. Keep a backup and test changes right away.
- Redirect chains and loops appear when old rules stay in the file after a migration.
- Rules are not applied because
AllowOverrideis off or the site runs on nginx. - A cache or CDN keeps serving the old response after an edit.
Sources
- Apache HTTP Server Tutorial: .htaccess files – Apache HTTP Server Projecthttpd.apache.org
- mod_rewrite – Apache HTTP Serverhttpd.apache.org
- Robots meta tag and X-Robots-Tag – Google Search Centraldevelopers.google.com
- .htaccess overview – DreamHost Help (secondary)help.dreamhost.com
Last updated: