Home Web ServerApache mod_rewrite Redirects: A Practical Ubuntu 24.04 Guide

Apache mod_rewrite Redirects: A Practical Ubuntu 24.04 Guide

by Knowledge Base Linux
Apache mod rewrite Redirects — Apache mod_rewrite Redirects: A Practical Ubuntu 24.04 Guide

Redirects are the quiet plumbing of the modern web: every HTTP-to-HTTPS upgrade, every www canonicalization, every old URL that still ranks in Google depends on them. On Ubuntu 24.04 with Apache 2.4, the module that does this work is apache mod_rewrite, a rule-based URL rewriting engine that can inspect requests, match patterns, and issue redirects with full control over status codes, query strings, and hostnames. In this practical guide you will enable the module, learn the half-dozen redirect recipes every sysadmin needs, and test them properly so you never ship a redirect loop to production.

apache mod_rewrite redirect rules branching from one page to new destinations, inspected with a magnifying glass

Prerequisites – Apache mod rewrite Redirects

  • An Ubuntu 24.04 server with the apache2 package installed and a working virtual host.
  • A user with sudo privileges.
  • A test domain or subdomain pointed at the server so you can verify redirects with curl.

Step 1: Enable apache mod_rewrite on Ubuntu 24.04 – Apache mod rewrite Redirects

Ubuntu ships mod_rewrite as a disabled-by-default module. Enable it with a2enmod and restart Apache:

sudo a2enmod rewrite
sudo systemctl restart apache2

Confirm the module is loaded:

apachectl -M | grep rewrite

You should see rewrite_module (shared) in the output. If it is missing, double-check that you restarted (not just reloaded) Apache after enabling the module. An apache mod_rewrite installation is useless until the module is actually loaded, so always verify with this check.

Step 2: Allow rewrite rules with AllowOverride

Rules placed in .htaccess files are only honored when the virtual host permits overrides. Edit your site config, for example /etc/apache2/sites-available/example.conf, and make sure the document-root directory block looks like this:

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

On a busy production server, consider putting rules directly in the <VirtualHost> block instead of .htaccess: Apache reads .htaccess on every request, while vhost-level rules are parsed once at startup. For this guide, .htaccess keeps things simple and portable.

Step 3: Redirect HTTP to HTTPS

The single most important apache mod_rewrite recipe forces every visitor onto TLS. Create or edit /var/www/example/.htaccess:

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

How it works: this apache mod_rewrite recipe checks whether the request arrived over plain HTTP via the condition, and the rule rebuilds the same URL with the https:// scheme. The R=301 flag issues a permanent redirect (which search engines prefer), and L stops further rule processing for this request. For more background on the TLS side of this setup, see our guide on redirecting HTTP to HTTPS with .htaccess.

Step 4: Canonicalize www and non-www

Pick one canonical hostname and redirect the other. To send all traffic to the www version:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

To do the reverse — strip www in favor of the bare domain — use:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [L,R=301]

The NC flag makes the hostname match case-insensitive, and %1 back-references the domain captured by the condition. Use exactly one of these two blocks, never both, or you will create the redirect loop described in the troubleshooting section.

Step 5: Redirect an old page to a new page with R=301

When content moves, preserve its SEO value with a permanent redirect from the old path to the new one:

RewriteEngine On
RewriteRule ^old-guide/?$ /new-guide/ [L,R=301]

The ^old-guide/?$ pattern matches /old-guide with or without a trailing slash and nothing else — the anchors ^ and $ prevent partial matches like /old-guide-extra from redirecting accidentally. The leading slash in the substitution is optional in .htaccess context but harmless. Stack several of these lines for a batch migration, most specific rules first.

Step 6: Handle query strings correctly

By default, apache mod_rewrite preserves the original query string on a redirect unless you say otherwise. To deliberately strip it — for example, when cleaning up tracking parameters on a canonical URL — end the substitution with a bare ?:

RewriteEngine On
RewriteCond %{QUERY_STRING} .
RewriteRule ^landing/?$ /landing? [L,R=301]

Conversely, the QSA (query string append) flag merges a new query string with the original one instead of replacing it:

RewriteRule ^search/?$ /results/?source=rewrite [L,R=301,QSA]

A request to /search/?q=apache then lands on /results/?source=rewrite&q=apache. When in doubt, test both behaviors with curl as shown in Step 8 — query-string surprises are a classic source of “it works in the browser” confusion. Getting apache mod_rewrite query-string behavior right saves hours of debugging later.

Step 7: Enforce a trailing slash

Duplicate content (/docs vs /docs/) dilutes SEO and splits analytics. This rule adds the trailing slash, but only when the request is not an actual file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)([^/])$ /$1$2/ [L,R=301]

The !-f condition is essential: without it, real files like /style.css would be “corrected” to /style.css/ and break. If your site also serves extensionless API endpoints, add RewriteCond %{REQUEST_FILENAME} !-d as well and test carefully.

Step 8: Test every rule before going live

Syntax-check the configuration, reload Apache, and then verify each redirect with curl:

sudo apachectl configtest
sudo systemctl reload apache2
curl -I http://example.com/old-guide
curl -I http://example.com/landing?utm_source=test

apachectl configtest must print Syntax OK. A correct 301 response looks like this:

HTTP/1.1 301 Moved Permanently
Location: https://example.com/new-guide/

Check three things: the status code is 301 (not 302, which does not pass full SEO value, and not 500), the Location header is exactly the URL you intended, and chained requests terminate — follow the chain with curl -IL and make sure it ends at a 200, not at another redirect. Test in a private browser window too, because browsers aggressively cache 301 responses and will happily show you yesterday’s rule.

Troubleshooting common apache mod_rewrite problems

Redirect loops (ERR_TOO_MANY_REDIRECTS)

A loop means two rules (or a rule plus the application) bounce the request back and forth. Typical causes: both www-to-non-www and non-www-to-www blocks active at once, or an HTTP-to-HTTPS rule behind a proxy where %{HTTPS} is always off. Inspect the chain with curl -IL, remove one of the conflicting rules, and for proxy setups match on %{HTTP:X-Forwarded-Proto} instead.

Rules are ignored entirely

Nine times out of ten this is AllowOverride None on the directory, or the rule living in a .htaccess file Apache never reads because the request is served from a different document root. Verify with a deliberate syntax error: if Apache does not complain, the file is not being parsed.

Missing L flag causes fall-through

Without [L], processing continues to the next rule and a later rule can rewrite the already-redirected URL. Add L to every redirect rule unless you have a specific reason to chain them.

500 Internal Server Error after editing

Almost always a syntax error in .htaccess. Run sudo apachectl configtest and read the exact line number in /var/log/apache2/error.log.

Query strings appear or vanish unexpectedly

Remember: the query string is preserved by default. Add the trailing ? to strip it, or QSA to merge it, as shown in Step 6.

Conclusion

With apache mod_rewrite enabled and these six recipes in your toolbox — HTTP to HTTPS, www canonicalization, page-to-page 301s, query-string control, trailing slashes, and proper testing with apachectl configtest and curl -I — you can handle nearly every redirect scenario an Ubuntu 24.04 server will throw at you. Keep rules minimal, order them from most specific to most general, and always verify the full redirect chain before declaring victory. When an apache mod_rewrite rule misbehaves, curl -IL is your best friend: it shows the exact chain of redirects so you can spot the loop in seconds. The authoritative reference for every flag and variable used here is the official Apache mod_rewrite documentation.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.