Operating System Ubuntu

How to Use .htaccess Files with Apache 2.4 on Ubuntu 26.04 LTS

Enable .htaccess for a site on Ubuntu 26.04 LTS, use it for redirects, rewrites, password protection and access rules, and learn when the virtual host is the better place.

A .htaccess file lets you change Apache's behaviour for one directory — redirects, rewrites, password protection, access rules — without touching the server configuration. This guide shows how to switch .htaccess support on for a site on Ubuntu 26.04 LTS with Apache 2.4, how to use it for the most common jobs, how to write access rules in the current Require syntax, and when you are better off without it. Everything applies unchanged to Ubuntu 24.04 LTS; the only difference is the Apache build (2.4.58 there, 2.4.66 on 26.04).

Ubuntu 18.04 has passed the end of its standard support, and instructions written for it often still use the Apache 2.2 access directives Order, Allow and Deny. Those are deprecated; the sections below use their replacement.

Requirements

  • Ubuntu 26.04 LTS or 24.04 LTS with Apache installed (sudo apt install apache2).
  • A user with sudo rights.
  • A site served from its own virtual host. The examples use example.com with the document root /var/www/example.com/public_html and the virtual host file /etc/apache2/sites-available/example.com.conf.

Step 1: Allow .htaccess files for the site

Apache ignores .htaccess files unless AllowOverride permits them, and the default in Apache 2.4 is AllowOverride None. Ubuntu's /etc/apache2/apache2.conf sets that explicitly for /var/www/, so on a fresh install your .htaccess does nothing. Leave the global file alone and enable overrides only for the site that needs them. Open the virtual host file:

sudo nano /etc/apache2/sites-available/example.com.conf

Add a <Directory> block inside the <VirtualHost> section:

<Directory /var/www/example.com/public_html>
    AllowOverride All
    Require all granted
</Directory>

AllowOverride All accepts every directive that is valid in a .htaccess file. If other people can upload files to the site, grant only the categories they need instead:

CategoryAllows
AuthConfigAuthentication and authorization: AuthType, AuthUserFile, Require
FileInfomod_rewrite rules, Redirect, ErrorDocument, Header, handlers and MIME types
IndexesDirectory listing appearance and DirectoryIndex
OptionsThe Options directive, for example Options -Indexes
LimitThe legacy Order, Allow, Deny directives

For example, AllowOverride FileInfo AuthConfig is enough for a typical CMS with a password-protected admin folder. A directive from a category you did not allow causes a 500 error for the whole directory.

Enable the modules the examples below rely on. mod_rewrite and mod_headers are installed but not enabled by default:

sudo a2enmod rewrite headers

Check the configuration and restart Apache so the new modules are loaded:

sudo apache2ctl configtest
sudo systemctl restart apache2

Step 2: Create the file and test it

Create the file in the document root. It applies to that directory and everything below it; a .htaccess in a subdirectory can override it for that subtree.

sudo nano /var/www/example.com/public_html/.htaccess

To prove Apache reads the file, put a nonsense word such as TestMe on the first line, save, and request any page of the site. You should get a 500 Internal Server Error. If the page loads normally, overrides are still disabled for this directory. Remove the line again afterwards.

Changes to a .htaccess file take effect on the next request. You do not reload Apache.

Common uses

Redirects

Send one old URL, or a whole old directory, to a new location with mod_alias:

Redirect 301 /old-page.html /new-page.html
RedirectMatch 301 ^/blog/(.*)$ https://example.com/articles/$1

Force HTTPS

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

Route requests through a front controller

Most PHP frameworks and CMSs send every request that is not a real file or directory to index.php:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

Inside a .htaccess file, rewrite patterns are matched against the path relative to the directory the file is in, without a leading slash. A rule copied from a virtual host that starts with ^/images/ has to become ^images/ in the document root's .htaccess.

Custom error pages and directory listings

ErrorDocument 404 /errors/404.html
Options -Indexes

Options -Indexes stops Apache from listing the contents of directories that have no index file.

Security headers

Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"

Password-protect a directory

Create a password file outside the document root. The -c flag creates the file, so leave it out when you add further users:

sudo apt install apache2-utils
sudo htpasswd -c /etc/apache2/.htpasswd deploy

Then put this in the .htaccess of the directory you want to protect:

AuthType Basic
AuthName "Restricted area"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user

Basic authentication sends the password with every request, so use it only on a site served over HTTPS.

Access control with Require

Apache 2.4 controls access with Require. In a .htaccess file it needs AllowOverride AuthConfig (or All).

Allow only one network:

Require ip 203.0.113.0/24

Allow everyone except one address. Negated rules have to sit inside a <RequireAll> block:

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

Block access to specific files, for example environment and backup files that should never be downloaded:

<FilesMatch "(^\.env|\.(bak|sql|log))$">
    Require all denied
</FilesMatch>

The table shows how the Apache 2.2 directives found in older tutorials translate:

Apache 2.2Apache 2.4
Order allow,deny + Allow from allRequire all granted
Order deny,allow + Deny from allRequire all denied
Order deny,allow + Deny from all + Allow from 203.0.113.0/24Require ip 203.0.113.0/24

The old directives only work through the compatibility module mod_access_compat, and the Apache documentation calls them deprecated. Do not mix old and new style in the same file; the result is hard to predict.

Performance: when not to use .htaccess

With overrides enabled, Apache looks for a .htaccess file in the requested directory and in every parent directory covered by AllowOverride, on every request, and parses whatever it finds again each time. Rewrite rules in .htaccess are also recompiled per request, whereas rules in the server configuration are compiled once at startup.

The Apache project's own advice is therefore to avoid .htaccess whenever you can edit the main configuration. On your own VPS you can. Any directive from a .htaccess file works the same inside the matching <Directory> block of the virtual host:

<Directory /var/www/example.com/public_html>
    AllowOverride None
    Require all granted

    Options -Indexes
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
</Directory>

After moving the rules, test and reload:

sudo apache2ctl configtest
sudo systemctl reload apache2

Keep .htaccess for the cases it was designed for: applications that ship and update their own rules, and users who manage a site without root access.

Troubleshooting

  • The file has no effect. AllowOverride is still None for that path, or the <Directory> path in the virtual host does not match the real document root. Use the TestMe check from step 2.
  • 500 Internal Server Error. Read the error log; it names the file and the directive:
    sudo tail -n 20 /var/log/apache2/error.log
    A message such as Invalid command 'RewriteEngine' means the module is not enabled (sudo a2enmod rewrite, then restart). not allowed here means the directive's category is missing from AllowOverride.
  • Rewrite rules do not match. Remove the leading slash from the pattern, as described above.
  • Visitors can download the file. They cannot on a default Ubuntu install: apache2.conf denies access to all files whose names start with .ht.

Frequently asked questions

Does Nginx read .htaccess files?

No. Nginx has no per-directory configuration files. If Nginx serves the site directly, the rules have to be translated into its own configuration; if Nginx is only a reverse proxy in front of Apache, the .htaccess files keep working in Apache.

Should I wrap directives in <IfModule>?

Only in files you distribute to servers you do not control. On your own server, <IfModule> hides the problem: if the module is missing, the rules are silently skipped instead of producing an error that tells you what to fix.

Can I use a different file name?

Yes, the AccessFileName directive in the server or virtual host configuration sets it. There is rarely a reason to: tools and applications expect .htaccess, and Ubuntu's rule that blocks downloads only covers names starting with .ht.

Is AllowOverride All a security risk?

It gives anyone who can write files into the directory control over handlers, rewrites and access rules for it. That is fine for a site only you deploy; on a server with untrusted uploaders or a compromised web application, it widens what an attacker can do. Granting specific categories, or using AllowOverrideList to permit individual directives, limits that.

Share story:

Continue reading other guides on How VPS.