Baeldung Pro – Linux – NPI EA (cat = Baeldung on Linux)
announcement - icon

Learn through the super-clean Baeldung Pro experience:

>> Membership and Baeldung Pro.

No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.

Partner – Orkes – NPI EA (tag=Kubernetes)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

1. Introduction

Redirecting URLs is a common task for website administrators, whether it’s to manage outdated pages, move content to a new domain, or ensure secure connections. Apache HTTP Server, one of the most popular web servers, offers powerful tools for URL redirection.

In this tutorial, we’ll explore how to create HTTP redirects in Apache 2.4 using virtual host configuration files. We’ll cover the different types of redirects, their use cases, and step-by-step examples for each method. By the end, we’ll be able to confidently set up redirects in an Apache server environment.

2. What Are HTTP Redirects?

An HTTP redirect informs a browser or client that a resource has moved to a new location. When users or bots access a URL, they’re automatically directed to the new one. There are several types of redirects, but the two most common are:

  • 301 Moved Permanently: Tells the browser that the URL has permanently moved. Search engines update their indexes to reflect the new URL, and browsers often cache the redirect to improve performance.
  • 302 Found (originally “Moved Temporarily” in HTTP/1.0): Indicates that the URL has temporarily moved. Search engines don’t update their indexes in this case.

Understanding which type of redirect to use is critical for maintaining SEO and user experience.

2.1. Other Types of Redirects

While 301 and 302 redirects are the most common, there are other types worth mentioning:

  • 303 See Other: Used when a resource has been replaced with another and is commonly associated with POST requests
  • 307 Temporary Redirect: Similar to 302 but preserves the HTTP method used in the original request
  • 308 Permanent Redirect: Similar to 301 but ensures the HTTP method remains the same

Each redirect type serves a specific purpose, so it’s essential to choose the right one based on the situation.

3. Using mod_alias for Simple Redirects

The mod_alias module in Apache is a built-in module that provides simple URL redirection and mapping capabilities. It allows us to easily redirect requests from one URL to another using directives like Redirect and RedirectMatch.

Unlike mod_rewrite, which is more powerful but complex, mod_alias is lightweight and best suited for straightforward, static redirects such as moving an old domain to a new one or redirecting specific pages.

Since mod_alias is included by default in Apache, it doesn’t require additional installation, making it a convenient choice for basic redirection needs.

Next, we’ll look at different use cases for implementing redirects.

3.1. Setting up a Permanent Redirect

Let’s see how to redirect a domain to another domain using the Redirect directive for creating a permanent redirect.

First, let’s open the virtual host configuration file for our site. For instance, if our site is example.com, we can edit its configuration file:

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

In the file, we’ll edit or add the following section to redirect all traffic to another domain:

<VirtualHost *:80>
    ServerName example.com
    Redirect 301 / https://www.anotherdomain.com/
</VirtualHost>

Once we’ve made the changes, let’s save the file and exit the editor. To ensure the configuration is valid, we can test it with the following command:

$ sudo apachectl configtest

If there are no errors, we can proceed to reload Apache to apply the changes:

$ sudo systemctl reload apache2

With this configuration, all traffic to example.com will be redirected to https://www.anotherdomain.com/ using a permanent redirect.

3.2. Redirecting Specific Paths

We can also redirect individual URLs by specifying the path in the Redirect directive:

<VirtualHost *:80>
    ServerName example.com
    Redirect 301 /old-page http://example.com/new-page
</VirtualHost>

This configuration ensures that only requests to /old-page are redirected to /new-page.

4. Using mod_rewrite for Advanced Redirects

The mod_rewrite module in Apache is a powerful and flexible tool for manipulating URLs based on defined patterns and conditions. It enables us to perform complex URL rewriting and redirection using regular expressions, making it ideal for dynamic sites, SEO-friendly URLs, and enforcing HTTPS.

Unlike mod_alias, which handles simple redirects, mod_rewrite can modify request URLs dynamically, enabling advanced routing and URL restructuring.

The mod_rewrite module is not always enabled by default. Therefore, let’s ensure the module is enabled. On Debian-based systems, we can enable it with:

$ sudo a2enmod rewrite
$ sudo systemctl reload apache2

On RHEL-based systems, we need to make sure the module is loaded by adding or uncommenting the following line in the Apache configuration file (usually located at /etc/httpd/conf/httpd.conf):

LoadModule rewrite_module modules/mod_rewrite.so

After making this change, we’ll restart Apache for the changes to take effect:

$ sudo systemctl restart httpd

With mod_rewrite enabled, we can now use it to create powerful and flexible redirect rules within our virtual host configuration.

4.1. Setting up a Temporary Redirect

We can use mod_rewrite to handle temporary redirects. For example, we can redirect all requests from an old directory to a new one:

<VirtualHost *:80>
    ServerName example.com
    RewriteEngine On
    RewriteRule ^old-directory/(.*)$ /new-directory/$1 [R=302,L]
</VirtualHost>

In this case, any request to old-directory will be redirected to the corresponding path in new-directory using a temporary redirect.

4.2. Redirecting HTTP to HTTPS

One of the most common uses of mod_rewrite is to enforce HTTPS. For example, we can redirect all HTTP requests to use HTTPS:

<VirtualHost *:80>
    ServerName example.com
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

This configuration redirects all HTTP requests to HTTPS, improving security.

4.3. Redirecting Non-www to www for Consistent URLs

Another powerful use of mod_rewrite is redirecting non-www URLs to their www equivalent, ensuring consistency and avoiding duplicate content issues. Particularly, this is useful for SEO and maintaining a uniform domain structure. Here’s how we can achieve this:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
</VirtualHost>

This configuration permanently redirects any request made to example.com without www to www.example.com. It helps maintain a consistent domain structure and improves SEO by avoiding duplicate content across multiple variations of the same URL.

5. Conclusion

In this article, we explored how to configure URL redirects in Apache using virtual host configuration files. In particular, we covered simple redirects using mod_alias for straightforward mappings and leveraged mod_rewrite for more advanced, flexible redirection rules.

By implementing these techniques, we can efficiently manage URL changes, enforce HTTPS, and maintain consistent domain structures. Understanding the right approach to redirection ensures better performance, security, and search engine rankings for our websites.