Mastering Redirection with mod_rewrite
in Apache
If you are managing a website that requires redirecting traffic from one domain to another while preserving access to certain paths, mod_rewrite
in Apache can be your best friend. In this post, we will tackle how to redirect all requests except one specific path, such as /audio
, using mod_rewrite
.
The Problem
Many webmasters find themselves in a situation where they need to redirect traffic to a new domain, but want to allow specific requests to go through without change. For instance, if you are transitioning from mydomain.example
to newdomain.example
, and you want all traffic redirected except requests for /audio
, that’s where mod_rewrite
comes in.
Common Syntax Issues
The original attempt made by a user to set up redirection included a complex use of regular expressions and advanced conditions. While the intention was correct, using the HTTP_HOST
in the RewriteCond
was misguided since it doesn’t include the request path.
The Solution
To achieve the desired redirection while allowing access to the /audio
path, your Apache configuration should be adjusted as follows:
Step-by-Step Configuration
-
Activate the Rewrite Engine: First, make sure that the rewrite engine is turned on.
RewriteEngine on
-
Set Up the Condition: Use the
REQUEST_URI
variable to check if the request is NOT for the/audio
path.RewriteCond %{REQUEST_URI} !^/audio
-
Define the Rewrite Rule: Create a rule that handles the redirection to the new domain.
RewriteRule ^(.*)$ http://www.newdomain.example [L,R=301]
Putting It All Together
In your VirtualHost
configuration, it should look something like this:
<VirtualHost *:80>
ServerAdmin me@mydomain.example
DocumentRoot "/var/www/mydomain.example/htdocs"
ServerName www.mydomain.example
ServerAlias mydomain.example
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/audio
RewriteRule ^(.*)$ http://www.newdomain.example [L,R=301]
RewriteLog /path/to/log/file
RewriteLogLevel 3
ErrorLog logs/error_log
CustomLog logs/access_log common
</VirtualHost>
Debugging Your Configuration
If you still encounter issues after setting this up, consider enabling logging to see the conditions and rules in action:
- Use the
RewriteLog
to specify a log file and set the log level high enough to capture relevant details.
RewriteLog /path/to/log/file
RewriteLogLevel 3
Understanding the Logs
When you check the logs after implementing the above rules, ensure that requests to /audio
do not hit the rewrite rule.
Conclusion
Setting up URL redirection using mod_rewrite
is a powerful way to manage traffic while ensuring specific paths remain accessible. By focusing on the correct configuration and understanding the behavior of REQUEST_URI
, you can solve issues related to unwanted redirects effectively.
With this guidance, you’re now equipped to handle URL redirections in Apache with confidence. Happy coding!