Nginx配置疑问:HTTPS无WWW域名未跳转至WWW及重定向循环问题
Hey there, let's sort out that frustrating redirect loop and get your non-www HTTPS traffic properly pointing to https://www.example.com for consistent SEO tracking. Here's the breakdown of the issue and step-by-step fixes:
First, Confirm Your SSL Certificate
Make sure your SSL certificate covers both example.com and www.example.com (either a SAN certificate or wildcard certificate). If it doesn't, visitors will hit certificate errors when accessing https://example.com before the redirect even happens—this is a critical prerequisite.
Update Your Server Configuration (Nginx Example)
The redirect loop usually happens because you tried handling both non-www and www HTTPS traffic in the same server block, making the redirect rule trigger even for valid www requests. Split them into separate blocks for precise control:
HTTP Server Block (Catch All Plain HTTP Traffic)
This handles all unencrypted requests (both non-www and www) and redirects them directly to the HTTPS www version:server { listen 80; server_name example.com www.example.com; return 301 https://www.example.com$request_uri; }HTTPS Server Block (Non-WWW Redirect)
This specifically targetshttps://example.comand redirects it to the www variant. Use the same SSL certificate as your main site:server { listen 443 ssl; server_name example.com; # Copy your SSL certificate config here ssl_certificate /path/to/your/fullchain.pem; ssl_certificate_key /path/to/your/privkey.pem; # Include shared SSL settings (like protocols/ciphers) if you have them # include /etc/nginx/ssl-params.conf; return 301 https://www.example.com$request_uri; }HTTPS Server Block (Main WWW Site)
This is your existing working configuration forhttps://www.example.com—keep all your site's root, location, and application logic here:server { listen 443 ssl; server_name www.example.com; # Same SSL certificate config as above ssl_certificate /path/to/your/fullchain.pem; ssl_certificate_key /path/to/your/privkey.pem; # include /etc/nginx/ssl-params.conf; # Your site's core configuration root /var/www/your-site; index index.html index.php; # Add your location blocks, proxy settings, etc. here location / { try_files $uri $uri/ =404; } }
Test the Fix
After updating the config, reload your server to apply changes:
sudo nginx -s reload
Verify the redirect works with this curl command:
curl -I https://example.com
You should see a 301 Moved Permanently response with Location: https://www.example.com/ (or the specific path you tested).
Why This Eliminates the Loop
By splitting HTTPS traffic into two separate server blocks, we ensure the redirect rule only runs when the request is for example.com (non-www). The main www server block handles valid https://www.example.com traffic without triggering any redirects, breaking the loop entirely.
内容的提问来源于stack exchange,提问作者user500963

