BLOG POSTS
    MangoHost Blog / How to Redirect www to Non-www with Apache on Ubuntu 24
How to Redirect www to Non-www with Apache on Ubuntu 24

How to Redirect www to Non-www with Apache on Ubuntu 24

Setting up proper URL canonicalization is crucial for SEO and user experience, and one of the most common requirements is redirecting www URLs to their non-www counterparts. This guide walks you through configuring Apache on Ubuntu 24 to automatically redirect www.yourdomain.com to yourdomain.com, covering multiple implementation methods, troubleshooting common issues, and optimizing for performance.

Why Redirect www to Non-www

Search engines treat www and non-www versions as separate domains, potentially splitting your SEO juice and creating duplicate content issues. Beyond SEO considerations, having a consistent URL structure improves user experience and simplifies analytics tracking.

The technical difference lies in DNS configuration – www is actually a subdomain that typically points to the same server as the root domain. However, from a web server perspective, Apache treats these as distinct virtual hosts unless explicitly configured otherwise.

Prerequisites and Environment Setup

Before diving into configuration, ensure your Ubuntu 24 system has Apache installed and the necessary modules enabled:

sudo apt update
sudo apt install apache2
sudo a2enmod rewrite
sudo systemctl restart apache2

Verify Apache is running and the rewrite module is loaded:

sudo systemctl status apache2
apache2ctl -M | grep rewrite

You should see rewrite_module in the output if everything is configured correctly.

Method 1: Virtual Host Configuration

The most robust approach involves creating separate virtual host configurations for both www and non-www versions. This method provides better control and cleaner separation of concerns.

Create or edit your main site’s virtual host file:

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

Add the following configuration:

<VirtualHost *:80>
    ServerName yourdomain.com
    DocumentRoot /var/www/html/yourdomain
    
    # Your main site configuration goes here
    ErrorLog ${APACHE_LOG_DIR}/yourdomain_error.log
    CustomLog ${APACHE_LOG_DIR}/yourdomain_access.log combined
</VirtualHost>

<VirtualHost *:80>
    ServerName www.yourdomain.com
    Redirect permanent / http://yourdomain.com/
</VirtualHost>

For HTTPS sites, you’ll need corresponding SSL virtual hosts:

<VirtualHost *:443>
    ServerName yourdomain.com
    DocumentRoot /var/www/html/yourdomain
    
    SSLEngine on
    SSLCertificateFile /path/to/your/certificate.crt
    SSLCertificateKeyFile /path/to/your/private.key
    
    # Your main HTTPS site configuration
</VirtualHost>

<VirtualHost *:443>
    ServerName www.yourdomain.com
    SSLEngine on
    SSLCertificateFile /path/to/your/certificate.crt
    SSLCertificateKeyFile /path/to/your/private.key
    
    Redirect permanent / https://yourdomain.com/
</VirtualHost>

Enable the site and restart Apache:

sudo a2ensite yourdomain.com.conf
sudo systemctl reload apache2

Method 2: .htaccess Approach

If you prefer using .htaccess files or don’t have access to Apache’s main configuration, this method works well within your document root:

sudo nano /var/www/html/yourdomain/.htaccess

Add these rewrite rules:

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

For sites using HTTPS, use this enhanced version that handles both HTTP and HTTPS:

RewriteEngine On

# Redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

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

Ensure your Apache configuration allows .htaccess overrides by checking your virtual host or main configuration includes:

<Directory /var/www/html/yourdomain>
    AllowOverride All
</Directory>

Method Comparison and Performance Considerations

Method Performance Flexibility Maintenance Server Access Required
Virtual Host Excellent High Low Yes
.htaccess Good Medium Medium No
Server-level redirect Excellent Low High Yes

Virtual host configuration offers the best performance since Apache processes the redirect at the server level without reading additional files. The .htaccess approach adds slight overhead as Apache must read and parse the file for each request, but the difference is negligible for most applications.

Handling Edge Cases and Advanced Scenarios

Real-world implementations often encounter specific challenges that require additional configuration:

Subdomain Preservation

If you have legitimate subdomains that should remain as-is while only redirecting www, use this more specific pattern:

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

Multiple Domains

For hosting multiple domains on the same server, create separate virtual host blocks or use conditional redirects:

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

Testing and Verification

After implementing your redirect configuration, thorough testing ensures everything works as expected:

# Test HTTP redirect
curl -I http://www.yourdomain.com

# Test HTTPS redirect  
curl -I https://www.yourdomain.com

# Test with specific paths
curl -I http://www.yourdomain.com/some/path

Look for HTTP status code 301 (permanent redirect) and verify the Location header points to the correct non-www URL. Online tools like HTTP Status Checker can also help verify redirect chains.

Common Issues and Troubleshooting

Several issues commonly arise when implementing www to non-www redirects:

  • Redirect Loops: Often caused by conflicting rewrite rules. Check for multiple .htaccess files in parent directories and ensure your rewrite conditions are specific enough.
  • HTTPS Certificate Errors: Your SSL certificate must cover both www and non-www versions. Use a wildcard certificate or ensure both domains are included in a SAN certificate.
  • Caching Issues: Browsers and CDNs may cache redirects. Clear browser cache and check CDN settings if redirects don’t appear to work immediately.
  • Module Not Loaded: Ensure mod_rewrite is enabled using sudo a2enmod rewrite followed by an Apache restart.

Check Apache error logs for detailed troubleshooting information:

sudo tail -f /var/log/apache2/error.log

Performance Optimization and Best Practices

Optimize your redirect implementation for better performance and maintainability:

  • Use 301 redirects: Permanent redirects pass SEO value and are cached by browsers, reducing server load.
  • Implement at server level: Virtual host configurations outperform .htaccess for high-traffic sites.
  • Monitor redirect chains: Avoid multiple redirects (www → non-www → HTTPS) by handling both transformations in a single rule.
  • Consider DNS-level solutions: For extremely high-traffic scenarios, DNS-based redirects can reduce server load entirely.

Security Considerations

Implementing redirects securely prevents potential vulnerabilities:

# Prevent open redirects by validating the host
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.yourdomain\.com$ [NC]
RewriteRule ^(.*)$ https://yourdomain.com/$1 [R=301,L]

# Add security headers
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
Header always set X-Content-Type-Options nosniff

Always validate that your redirect rules can’t be exploited for open redirect attacks by using specific domain matching rather than generic patterns.

Integration with Modern Deployment Workflows

Modern applications often use containerized deployments or configuration management tools. Here’s how to integrate these redirects:

For Docker deployments, include your Apache configuration in the Dockerfile:

COPY yourdomain.com.conf /etc/apache2/sites-available/
RUN a2ensite yourdomain.com.conf && a2enmod rewrite

For Ansible automation, use the apache2_module and template modules:

- name: Enable rewrite module
  apache2_module:
    name: rewrite
    state: present
  notify: restart apache2

- name: Configure virtual host
  template:
    src: yourdomain.com.conf.j2
    dest: /etc/apache2/sites-available/yourdomain.com.conf
  notify: reload apache2

The www to non-www redirect is a fundamental aspect of web server configuration that impacts SEO, user experience, and site consistency. By implementing these configurations correctly and following best practices, you ensure your Ubuntu 24 Apache server handles URL canonicalization efficiently and securely.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked