Apache Rewrite配置求助:域名及子路径无法跳转至HTTPS带WWW地址
Hey there! It sounds like your current redirect setup only handles the root domain and fails to carry over specific paths (like /hello) to the target URL. Let’s fix this using Apache’s mod_rewrite to ensure every request—whether it’s the root or a nested path—gets redirected correctly to the HTTPS www version with the full URI intact.
Step 1: Enable mod_rewrite (if not already active)
First, make sure the rewrite module is turned on. On Debian/Ubuntu-based systems, run these commands:
sudo a2enmod rewrite sudo systemctl restart apache2
Step 2: Update Your Virtual Host Configuration
Replace your existing relevant config with this snippet. This handles both non-www → www and HTTP → HTTPS redirects while preserving the full request path:
<VirtualHost *:80> ServerName www.123abc.com ServerAlias 123abc.com # Turn on rewrite engine RewriteEngine On # Redirect all requests to HTTPS www version, keeping the full path RewriteCond %{HTTP_HOST} !^www\.123abc\.com$ [OR] RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://www.123abc.com$1 [R=301,L] # Keep your existing DocumentRoot line here DocumentRoot "/mnt/..." </VirtualHost> # Don't forget your HTTPS virtual host for the target domain <VirtualHost *:443> ServerName www.123abc.com DocumentRoot "/mnt/..." # Add your SSL certificate configuration here SSLEngine On SSLCertificateFile /path/to/your/certificate.pem SSLCertificateKeyFile /path/to/your/private-key.pem # ... any other SSL settings you need ... </VirtualHost>
What Each Part Does
RewriteCond %{HTTP_HOST} !^www\.123abc\.com$ [OR]: Checks if the request is coming to the non-www version of the domain.RewriteCond %{HTTPS} off: Checks if the request is over unencrypted HTTP.RewriteRule ^(.*)$ https://www.123abc.com$1 [R=301,L]: Captures the entire request path ((.*)) and appends it to the target URL ($1is the captured path).R=301is a permanent redirect (good for SEO), andLtells Apache to stop processing further rules after this one.
This setup will correctly handle all these cases:
http://123abc.com→https://www.123abc.comhttp://www.123abc.com/hello→https://www.123abc.com/hellohttps://123abc.com/hello/world→https://www.123abc.com/hello/world
After updating the config, restart Apache to apply changes:
sudo systemctl restart apache2
内容的提问来源于stack exchange,提问作者acctman

