0

I'm fixing my Apache (2.4.12) config files on a server that serves three different domain names. I have a different config file for each site. I cannot for the life of me figure out how to accomplish both of the following:

  1. Redirect all http requests to https, keeping the entire rest of the request (subdomain/host AND document path) exactly the same
  2. Redirect all www requests to non-www

I've read that this can be done in one step if I have only one *:80 VirtualHost and put the rewrite rules there (the remainder of my subdomains are all *:443 VirtualHosts with the exception of www), but I can't figure out how to do it. These answers on SO did not work:

  • The accepted answer in this question is not correct (only does the https redirect)
  • This answer does not work for me--only the https redirect works.
  • This question doesn't deal with a wildcard subdomain and is thus inapplicable.
  • This question is also inapplicable because it doesn't deal with subdomains.

EDIT: This is the code I reference in the comments for mike.k's answer below.

<VirtualHost *:80>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} www.example.com
    RewriteRule ^(.*)$ https://example.com/$1 [R=permanent,L]

    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://example.com%{REQUEST_URI}
</VirtualHost>
vaindil
  • 7,536
  • 21
  • 68
  • 127

1 Answers1

1

This is from my production system and works.

THE_HOSTNAME is for instance server, and then THE_FQHN is server.domain.edu, which helps for SSL certificates if you don't want to support wildcards and multiple domain names.

# redirect to FQHN
RewriteEngine on
RewriteCond %{HTTP_HOST} THE_HOSTNAME$
RewriteRule ^(.*)$ https://THE_FQHN/ $1 [R=permanent,L]

# redirect to HTTPS
RewriteCond %{HTTPS} off
RewriteRule (.*) https://THE_FQHN%{REQUEST_URI}

In your case www.domain.com would be where THE_HOSTNAME is, and THE_FQHN would be domain.com, just flipped around

mike.k
  • 3,277
  • 1
  • 12
  • 18
  • It appears that the `$1` on line 4 of your code shouldn't have a space before it (I get a syntax error). I'm testing now though and I'll let you know if it works with that space removed. – vaindil Jul 12 '15 at 16:10
  • Unfortunately, it doesn't work. I used your code exactly how you put it (with the `$1` fixed per my previous comment) but with my hostname info. The `https` redirect works correctly, but the `www` isn't removed. I'm adding the exact setup to the OP so you can see it. – vaindil Jul 12 '15 at 16:13
  • You were right about the space, I introduced it with careless typing. Put the `$` at the end of `www.example.com` in your Edit, so `RewriteCond %{HTTP_HOST} www.example.com$` – mike.k Jul 12 '15 at 17:18