BLOG POSTS
    MangoHost Blog / How to Redirect www to Non-www with Nginx on latest CentOS
How to Redirect www to Non-www with Nginx on latest CentOS

How to Redirect www to Non-www with Nginx on latest CentOS

Redirecting www to non-www versions of your website is a crucial SEO and user experience consideration that consolidates domain authority and prevents duplicate content issues. When search engines encounter both www.example.com and example.com serving identical content, they might treat these as separate sites, potentially diluting your SEO rankings. In this comprehensive guide, you’ll learn how to properly configure Nginx on the latest CentOS to automatically redirect www traffic to your non-www domain, including advanced configurations, troubleshooting common issues, and implementing best practices for production environments.

How WWW to Non-WWW Redirection Works

The www to non-www redirect functions at the HTTP server level through the implementation of 301 redirects, which inform both browsers and search engines that the www version has permanently moved to the non-www variant. Nginx handles this redirection through server blocks that specifically listen for requests containing the www subdomain and respond with appropriate redirect headers.

When a user requests www.example.com, Nginx matches this against configured server blocks, identifies it as a redirect candidate, and returns an HTTP 301 status code along with the Location header pointing to example.com. This process occurs before any content is served, ensuring minimal performance impact while maintaining SEO integrity.

The technical flow involves DNS resolution, where both www and non-www versions point to your server’s IP address, followed by Nginx’s server block evaluation based on the server_name directive. The redirect happens during the initial request processing phase, making it extremely efficient.

Prerequisites and Environment Setup

Before implementing the redirect configuration, ensure you have a properly functioning Nginx installation on CentOS. You’ll need root or sudo privileges, and both your www and non-www domains should already be pointing to your server through DNS configuration.

First, verify your current Nginx installation and check the version:

nginx -v
systemctl status nginx

If Nginx isn’t installed, install it on the latest CentOS using:

sudo dnf update
sudo dnf install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

Confirm your firewall allows HTTP and HTTPS traffic:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Step-by-Step Implementation Guide

The most effective approach involves creating a dedicated server block specifically for handling www redirects. This method provides clean separation of concerns and makes configuration management more straightforward.

Navigate to your Nginx configuration directory and create or modify your site configuration:

cd /etc/nginx/conf.d/
sudo nano example.com.conf

Implement the basic redirect configuration:

server {
    listen 80;
    listen [::]:80;
    server_name www.example.com;
    return 301 http://example.com$request_uri;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    
    root /var/www/html/example.com;
    index index.html index.htm index.php;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

For HTTPS implementations, which are essential for modern web applications, expand the configuration to handle SSL certificates:

server {
    listen 80;
    listen [::]:80;
    server_name www.example.com example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name www.example.com;
    
    ssl_certificate /path/to/your/certificate.crt;
    ssl_certificate_key /path/to/your/private.key;
    
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com;
    
    ssl_certificate /path/to/your/certificate.crt;
    ssl_certificate_key /path/to/your/private.key;
    
    root /var/www/html/example.com;
    index index.html index.htm index.php;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

After making configuration changes, test the syntax and reload Nginx:

sudo nginx -t
sudo systemctl reload nginx

Advanced Configuration Options

For high-traffic websites, consider implementing more sophisticated redirect strategies that include performance optimizations and additional security measures.

Enhanced configuration with security headers and caching directives:

server {
    listen 80;
    listen [::]:80;
    server_name www.example.com;
    
    # Security headers for redirect responses
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options DENY;
    
    # Cache redirect responses
    expires 1y;
    add_header Cache-Control "public, immutable";
    
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name www.example.com;
    
    # SSL configuration
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;
    
    # HSTS header
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    return 301 https://example.com$request_uri;
}

For content management systems or applications with complex URL structures, you might need conditional redirects:

server {
    listen 443 ssl http2;
    server_name www.example.com;
    
    ssl_certificate /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;
    
    # Preserve query parameters and fragments
    location / {
        return 301 https://example.com$request_uri;
    }
    
    # Special handling for API endpoints
    location /api/ {
        return 301 https://api.example.com$request_uri;
    }
}

Real-World Examples and Use Cases

Consider a WordPress multisite installation where you need to handle multiple domains with consistent redirect patterns. The configuration becomes more complex but follows the same principles:

server {
    listen 80;
    server_name www.site1.com www.site2.com www.site3.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name www.site1.com;
    ssl_certificate /etc/ssl/certs/site1.com.crt;
    ssl_certificate_key /etc/ssl/private/site1.com.key;
    return 301 https://site1.com$request_uri;
}

server {
    listen 443 ssl http2;
    server_name www.site2.com;
    ssl_certificate /etc/ssl/certs/site2.com.crt;
    ssl_certificate_key /etc/ssl/private/site2.com.key;
    return 301 https://site2.com$request_uri;
}

E-commerce platforms often require special handling for session preservation and analytics tracking. Here’s an approach that maintains shopping cart state:

server {
    listen 443 ssl http2;
    server_name www.shop.example.com;
    
    ssl_certificate /etc/ssl/certs/shop.example.com.crt;
    ssl_certificate_key /etc/ssl/private/shop.example.com.key;
    
    # Preserve session cookies during redirect
    proxy_cookie_domain www.shop.example.com shop.example.com;
    
    location / {
        return 301 https://shop.example.com$request_uri;
    }
}

Performance Optimization and Monitoring

Redirect performance directly impacts user experience and SEO rankings. Monitoring redirect chains and response times helps identify potential bottlenecks.

The following table compares different redirect methods and their performance characteristics:

Method Response Time (ms) Memory Usage CPU Impact Scalability
return 301 1-3 Minimal Very Low Excellent
rewrite permanent 2-5 Low Low Good
proxy_pass redirect 5-15 Medium Medium Fair
PHP-based redirect 50-200 High High Poor

Enable Nginx logging to monitor redirect performance:

server {
    listen 80;
    server_name www.example.com;
    
    access_log /var/log/nginx/www-redirect.log combined;
    error_log /var/log/nginx/www-redirect-error.log;
    
    return 301 https://example.com$request_uri;
}

Use tools like curl to verify redirect behavior and measure response times:

curl -I -w "Total time: %{time_total}s\n" http://www.example.com
curl -I -w "Total time: %{time_total}s\n" https://www.example.com

Comparison with Alternative Solutions

While Nginx provides excellent redirect capabilities, understanding alternative approaches helps you choose the optimal solution for your specific requirements.

Solution Performance Flexibility Maintenance Resource Usage
Nginx return directive Excellent High Low Minimal
Apache mod_rewrite Good Very High Medium Medium
Cloudflare Page Rules Excellent Medium Very Low None
Application-level redirects Poor Very High High High

DNS-based solutions like Cloudflare offer redirect capabilities with global edge caching, reducing server load entirely:

  • Cloudflare Page Rules can handle redirects at the edge, improving global response times
  • AWS CloudFront and similar CDNs provide redirect capabilities with geographic optimization
  • These solutions work well for high-traffic sites but introduce external dependencies

Troubleshooting Common Issues

Redirect loops represent the most frequent problem when implementing www to non-www redirects. These occur when conflicting rules create circular redirect patterns.

Debug redirect loops by examining your server block configurations for overlapping server_name directives:

nginx -T | grep -A 10 -B 5 "server_name.*example.com"

Common issues and their solutions:

  • Redirect loops: Ensure server_name directives don’t overlap between redirect and main server blocks
  • SSL certificate errors: Verify certificates cover both www and non-www versions, or use wildcard certificates
  • Mixed content warnings: Implement HTTPS redirects for all traffic, not just specific paths
  • Performance degradation: Use return directives instead of rewrite rules for better performance

When SSL certificates cause issues, check certificate validity for both domains:

openssl s_client -connect www.example.com:443 -servername www.example.com
openssl s_client -connect example.com:443 -servername example.com

For debugging complex configurations, enable detailed error logging:

error_log /var/log/nginx/error.log debug;

Security Considerations and Best Practices

Implementing redirects securely prevents potential attack vectors and ensures consistent security policy enforcement across your domain variations.

Security-enhanced redirect configuration:

server {
    listen 80;
    listen [::]:80;
    server_name www.example.com;
    
    # Security headers
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options DENY always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # Prevent access to sensitive files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
    
    return 301 https://example.com$request_uri;
}

Best practices for production environments:

  • Always use 301 redirects for permanent www to non-www redirections to preserve SEO value
  • Implement HSTS headers to prevent protocol downgrade attacks
  • Use HTTP/2 where possible to improve performance for subsequent requests
  • Monitor redirect chains to ensure they don’t exceed 3-5 hops
  • Test redirects regularly using automated monitoring tools
  • Document your redirect strategy for team members and future maintenance

For high-availability setups, consider implementing health checks that verify redirect functionality:

#!/bin/bash
# Simple redirect health check script
RESPONSE=$(curl -I -s -w "%{http_code}" -o /dev/null http://www.example.com)
if [ "$RESPONSE" != "301" ]; then
    echo "Redirect health check failed: HTTP $RESPONSE"
    exit 1
fi
echo "Redirect health check passed"

Regular monitoring ensures your redirect configuration continues working correctly as your infrastructure evolves. Consider implementing automated testing that validates redirect behavior after configuration changes, and maintain backup configurations for quick rollback capabilities.

For comprehensive server management and hosting solutions that support advanced Nginx configurations, explore VPS hosting options that provide full root access for custom server configurations, or consider dedicated servers for high-traffic applications requiring maximum performance and control.

Additional resources for advanced Nginx configuration include the official Nginx documentation and the comprehensive server names documentation for complex domain handling scenarios.



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