Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - htaccess force https and redirect www to non-www, but no other subdomains

I know there are many similar threads, but none of them seems to match my exact problem. Here is what I’m trying to do:

(1) http://www.mydomain.com/ -> https://mydomain.com/
(2) http://mydomain.com/     -> https://mydomain.com/
(3) https://www.mydomain.com -> https://mydomain.com/

Ideally, I would also like to cover the situation if I will ever add more subdomains, to automatically behave like the following (preferably in a generic way that will work for any subdomain I add).

(4) http://sub.mydomain.com/ -> https://sub.mydomain.com/

At this point I’m wondering if it is even possible to create a single .htaccess file that does everything I need, although I have to admit that I understand regexes, but I’m not exactly a mod_rewrite uberpro.

Here are the solutions that I already tried:

My SSL certificate covers the www-subdomain, so I’m not looking for a 'untrusted connection' error solution, I’m aware that isn’t possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found most of the suggestions were not catching when you had something that was https://www.example.com and redirecting to https://example.com.

The following worked for all permutations:

RewriteEngine On

# match any URL with www and rewrite it to https without the www
RewriteCond %{HTTP_HOST} ^(www.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [L,R=301]

# match urls that are non https (without the www)
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^(www.)(.*) [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Hope this helps someone!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...