如何移除网站首页多次重定向,实现直接跳转至HTTPS域名?
Got it, let's fix that double redirect issue once and for all! The goal is to send visitors straight from http://example.com to https://www.example.com without that extra hop to http://www.example.com.
First, let's break down the root cause: your current setup runs two separate redirects—first non-www HTTP → www HTTP, then www HTTP → www HTTPS. We need to combine these into one single, efficient redirect.
Below are tailored solutions for the most common server and CDN environments:
Apache (.htaccess)
If you're using Apache, edit your root .htaccess file and replace any existing redirect rules with this:
RewriteEngine On # Directly redirect non-www HTTP to www HTTPS RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301] # Fallback rule for any leftover www HTTP requests RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC] RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
- Use
R=301(permanent redirect) for SEO benefits—only switch toR=302if you need a temporary redirect. - Ensure
mod_rewriteis enabled on your Apache server.
Nginx
For Nginx, update your server block configuration (typically in /etc/nginx/sites-available/) with these blocks:
# Handle non-www HTTP requests with direct redirect server { listen 80; server_name example.com; return 301 https://www.example.com$request_uri; } # Fallback for www HTTP requests server { listen 80; server_name www.example.com; return 301 https://www.example.com$request_uri; } # Your main HTTPS server block (keep your existing SSL config here) server { listen 443 ssl; server_name www.example.com; # Add your SSL certificate paths, root directory, and other site configs here }
After editing, test the config with nginx -t then reload Nginx with systemctl reload nginx.
Cloudflare (CDN Users)
If you use Cloudflare, you can set up the redirect directly in their dashboard without touching server files:
- Go to your Cloudflare dashboard → Rules → Page Rules
- Create a new rule:
- URL:
http://example.com/* - Setting: Forwarding URL → 301 Permanent Redirect
- Destination URL:
https://www.example.com/$1
- URL:
- Save the rule, and ensure your Cloudflare SSL setting is set to Full or Strict (Flexible can cause redirect loops).
Key Testing Tips
- Use
curl -I http://example.comin your terminal to check response headers—you should see a single301 Moved Permanentlypointing directly tohttps://www.example.com. - Browsers cache permanent redirects, so test in incognito mode or clear your cache if you still see the old double redirect behavior.
内容的提问来源于stack exchange,提问作者Vinod Kumar

