Keywords: .htaccess redirection | mod_rewrite configuration | domain canonicalization
Abstract: This technical article provides an in-depth analysis of implementing correct redirection from non-www to www domains using Apache's .htaccess file. Through examination of common redirection errors, the article explores proper usage of RewriteRule capture groups and replacement strings, while offering comprehensive solutions supporting HTTP/HTTPS protocols and multi-level domains. The discussion includes protocol preservation and URL path handling considerations to help developers avoid common configuration pitfalls.
Problem Background and Common Errors
In web development, unifying domain formats is crucial for SEO and user experience. Many developers attempt to implement redirection from non-www to www domains using Apache's mod_rewrite module in .htaccess files, but often encounter path handling issues.
A typical erroneous configuration example:
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com$1 [R=301,L]
When accessing http://example.com/robots.txt, this configuration produces incorrect redirection to http://www.example.comrobots.txt/. The issue lies in the missing slash separator in the replacement string.
Basic Solution
The most direct method to correct this problem is adding a slash in the target URL:
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
Key improvements in this corrected solution include:
- Adding a slash after
www.example.com/to ensure proper path concatenation - Including
[NC]flag for case-insensitive matching - Using capture group
(.*)to match all request paths - Referencing captured path content through
$1
Universal Domain Solution
For scenarios requiring support for arbitrary domains, a more generic configuration approach can be employed:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Advantages of this approach:
- Using
!^www\.condition to match all domains not starting with www - Dynamically obtaining current domain through
%{HTTP_HOST} - Suitable for any domain configuration without hardcoding specific domains
Protocol Preservation and Advanced Configuration
In modern web environments, supporting HTTPS protocol has become increasingly important. The following configuration maintains the original request protocol:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Characteristics of this advanced configuration:
- Using
%{HTTPS}to detect whether current connection uses SSL - Referencing condition match results through
%1to dynamically select http or https - Using
%{REQUEST_URI}to obtain complete request path, avoiding path concatenation errors
Multi-level Domain Support
For multi-level domains including country codes (such as .co.uk), the matching condition needs adjustment:
RewriteCond %{HTTP_HOST} ^[^.]+\.\.[^.]+\.\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
This configuration uses more precise regular expressions to match multi-level domain structures, ensuring correct redirection logic.
Technical Principle Deep Analysis
The mod_rewrite module operates based on condition matching and rule rewriting. When Apache processes requests:
- First checks RewriteCond conditions, executing RewriteRule only when all conditions are true
- In RewriteRule,
^(.*)$matches the entire request path and stores the result in$1 - Variables in replacement strings (such as
%{HTTP_HOST},$1) are replaced with actual values at runtime [R=301]flag indicates sending 301 permanent redirection status code[L]flag signifies this is the last rule, preventing interference from subsequent rules
Best Practice Recommendations
When implementing domain redirection, following these best practices is recommended:
- Always use 301 redirects instead of 302 for better SEO weight transfer
- Test redirection logic in development environment first to avoid production configuration errors
- Consider using
%{REQUEST_URI}instead of capture groups to avoid path handling complexity - Ensure protocol consistency after redirection in mixed HTTP/HTTPS environments
- Regularly check server logs to monitor redirection errors and anomalies
By properly configuring .htaccess redirection rules, website domain uniformity can be ensured, enhancing user experience and search engine optimization. Understanding mod_rewrite working principles and common pitfalls helps developers build more robust web applications.