Apache2配置www域名重定向至非www域名失败求助
Hey Joseph, let's work through why your redirect from https://www.dolgins.com to https://dolgins.com isn't taking effect, and make sure the target URL shows correctly in the browser.
1. Verify mod_rewrite is enabled
First, Apache's rewrite module needs to be active for your .htaccess rules to work. Run these commands to enable it and restart Apache:
sudo a2enmod rewrite sudo systemctl restart apache2
2. Ensure .htaccess is allowed in your Virtual Host
If your Apache Virtual Host configuration doesn't permit overriding settings via .htaccess, your rules will be ignored. Open your SSL Virtual Host file (usually located at /etc/apache2/sites-available/your-site-le-ssl.conf or similar) and add/update the <Directory> block for your DocumentRoot:
<VirtualHost *:443> ServerName dolgins.com ServerAlias www.dolgins.com DocumentRoot /path/to/your/documentroot <Directory /path/to/your/documentroot> AllowOverride All # This is critical for .htaccess to work Require all granted </Directory> # Keep your existing SSL configuration (SSLCertificateFile, SSLCertificateKeyFile, etc.) </VirtualHost>
After making changes, restart Apache again:
sudo systemctl restart apache2
3. Adjust .htaccess rules for reliability
Your current rules are close, but let's tweak them to explicitly handle HTTPS and avoid unintended matches:
RewriteEngine On RewriteBase / # Redirect www.dolgins.com to non-www HTTPS RewriteCond %{HTTP_HOST} ^www\.dolgins\.com$ [NC] RewriteRule ^(.*)$ https://dolgins.com/$1 [R=301,L] # Optional: Catch any remaining HTTP requests and redirect to HTTPS RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://dolgins.com/$1 [R=301,L]
Using the full domain in the condition prevents accidental matches with other subdomains, and the second rule ensures all traffic lands on secure non-www.
4. Clear browser cache (critical for 301 redirects)
Since 301 Permanent Redirects are aggressively cached by browsers, test your redirect in a private/incognito window or clear your browser's cache entirely to see if the changes take effect.
5. Confirm SSL coverage for both domains
Make sure your SSL certificate includes both dolgins.com and www.dolgins.com (a SAN certificate). If you used Let's Encrypt, reissue the cert with both domains if you didn't include them initially—SSL errors can block the redirect from working as expected.
Ensuring the target URL displays correctly
The [R=301,L] flag in your rewrite rule already tells the browser to replace the address bar URL with https://dolgins.com. As long as the redirect fires properly (no conflicting rules or SSL issues), the non-www domain will show up in the browser once the redirect completes.
If you're still stuck, double-check that your A records for both domains point to the same server IP, and make sure there are no conflicting rewrite rules in other .htaccess files or Virtual Host configurations.
内容的提问来源于stack exchange,提问作者Joe D

