简体   繁体   中英

httpd.conf rewrite https://example.com to https://www.example.com

In httpd.conf, I have written rules in httpd.conf to redirect from insecure to secure, (eg, http://example.com -> https://www.example.com ),

but how do you prepend www when the site is already https?

For example, if I go to my browser and type in https://example.com I cannot find a way for apache to rewrite that as https://www.example.com . Instead I get a certificate error because my certificate is only good for "www.example.com" domain.

My current trial is:

AllowOverride All
RewriteEngine On
# If www is not present:
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC,OR]
# ... or if https is not present:
RewriteCond %{HTTPS} off
# ensure www and https both present
RewriteRule .? https://www.example.com%{REQUEST_URI} [NC,L]

The above does not prepend "www" when I enter in " https://example.com " (desiring a result of https://www.example.com )

What I think is happening: My initial request to https://example.com brings up a certificate mismatch error before the redirect can be acted upon.

Side issue: I cannot get google to accept a self-signed *.example.com certificate. If a wildcard cert worked, the above would not be an issue.

You need to use R flag to redirect from non-www to www, and an extra rule to redirect from non-www to www on SSL.

AllowOverride All
RewriteEngine On
# ...if  https is not present:
RewriteCond %{HTTPS} off
# ensure www and https both present
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NC,L,R]
#Redirect non-www to www on SSL
 RewriteCond %{HTTPS} on
 RewriteCond %{HTTP_HOST} !^www\.
 RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NC,L,R]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM