如何用.htaccess实现HTTP转HTTPS?调整重定向至https://www.example.com
Redirect HTTP to HTTPS + WWW via .htaccess
Got it, let's fix your .htaccess so all traffic lands on https://www.example.com—whether someone types in http://example.com, example.com, or even http://www.example.com. Here's the updated configuration that keeps your existing settings while adding the correct redirect logic:
RewriteOptions inherit #set link auto on Options +FollowSymLinks -MultiViews DirectoryIndex index.php index.html Options -Indexes RewriteEngine on # Skip redirects for cPanel domain validation files RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\..*)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\..*)?$ # Redirect non-www to www AND HTTP to HTTPS RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # Redirect HTTP to HTTPS for existing www requests RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Key Changes Explained:
- cPanel Validation Exclusions: I kept (and completed) the existing rules that skip redirects for cPanel's domain verification files. This ensures your SSL certificate doesn't break during renewal checks.
- Non-WWW to WWW + HTTPS: The first redirect rule catches any request without the
wwwprefix (even if it's already HTTPS) and sends it to the secure www version. - HTTP to HTTPS for WWW: The second rule handles cases where someone directly visits
http://www.example.com, ensuring they're redirected to the HTTPS variant. - Permanent Redirect: Using
R=301tells search engines this is a permanent change, which helps preserve your SEO rankings.
A quick note: After updating your .htaccess, clear your browser cache before testing—old redirects might be cached and give you false results. If you're using a CDN, you might need to purge its cache too.
内容的提问来源于stack exchange,提问作者rakeshkumar
相关产品推荐
相关产品推荐

