2

I want to know if it's possible to make a Rewrite Condition for if the %{HTTP_HOST} is NOT the ServerName or any of the listed ServerAlias.

My goal is to redirect any requests made to a domain that is not listed as the ServerName, ServerAlias', or direct to the IP (http://1.1.1.1, https://1.1.1.2. etc...).


Currently I achieve this by doing the following as part of my non-SSL to SSL redirection. After my non-SSL to SSL redirect rules I have a catch all rule where if the {HTTP_HOST} is not example.com then forward to my real domain.

I have similar rewrite rules in place for my SSL traffic where I have my catch all rule after my non-WWW to WWW rewrite rules.

<VirtualHost *:80>
ServerName  domain1.com
ServerAlias domain2.com domain3.com
DocumentRoot /home/domain/public_html
RewriteEngine on
RewriteCond %{SERVER_NAME} =domain1.com [OR]
RewriteCond %{SERVER_NAME} =domain2.com [OR]
RewriteCond %{SERVER_NAME} =domain3.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,NE,R=permanent]
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^(.*)$ https://domain1.com$1 [R=301,NC]
</VirtualHost>

Im curious if there is a better implementation for the last rewrite rule where if HTTP_HOST is NOT any of the listed ServerAlias' or ServerName.

My web app is used for simple network testing (ping my ip, traceroute, etc...) so the multiple IP addresses are easily obtainable by the user. I just want to make sure that any request made that is not using one of the listed Server addresses or sent directly to the IP address is redirected to my primary domain. The above does work I just want to know if there is a better way.

Analog
  • 202
  • 2
  • 12

1 Answers1

4

You're overthinking this. You don't need to put all the logic in RewriteConds.

When Apache gets a request for a host that doesn't match any of the ServerName or ServerAlias directives in any of the VirtualHosts, it will use the default VirtualHost - i.e. the one that's first in the configuration. So just put your rewrite rule in a separate VirtualDomain and make sure that one is loaded first, either by listing it first in the configuration file, or by naming it e.g. `00-default.conf' in the directory where you keep your VirtualHosts.

Since the configuration in that VirtualHost will only be used when someone connects and uses a domain name that's not otherwise listed, you don't need to negate any of the other domain names. The configuration can simply be

<VirtualHost *:80>
ServerName  default.example.net
DocumentRoot /home/domain/public_html
RewriteEngine on
RewriteRule ^(.*)$ https://example.com$1 [R=301,NC]
</VirtualHost>

See https://serverfault.com/a/520201/120438 for a more verbose explanation of how Apache chooses which VirtualHost to use.

Jenny D
  • 27,358
  • 21
  • 74
  • 110
  • With this approach, you can also use the simpler mod_alias `Redirect`, instead of having to resort to mod_rewrite. – MrWhite Jun 26 '18 at 23:33