4

I have several servers with different IP addresses. I want to make it impossible to reach them via IP directly. Instead, I want them to redirect to my domain, www.site.com.

The following condition matches an exact IP:

RewriteCond %{REMOTE_HOST} !^123\.456\.789\.012$

How can I match any IP using Apache rewrite rules?

ty.
  • 10,924
  • 9
  • 52
  • 71

4 Answers4

8

Note, you were using the wrong tag. It's not REMOTE_HOST as this is the user's ip. You need HTTP_HOST to get the server's IP.

For example::

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^\d+\.
RewriteRule (.*) http://www.example.com/$1 [R=301]

Edit, you can use a more specific regex if you want to. The main problem was your original tag.

Edit2:

If you have the list of specific IPs you want to redirect then you can use

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^111\.111\.111\.111 [OR]
RewriteCond %{HTTP_HOST} ^222\.222\.222\.222
RewriteRule (.*) http://www.example.me/$1 [R=301]
AlanFoster
  • 8,156
  • 5
  • 35
  • 52
2

If the regex is all you need, you can try replacing the !^123\.456\.789\.012$ by:

!^[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}\.[0-9]{0,3}$

This will match the characters between 0-9 (numerical characters) from 0 up to 3 times between each literal dot, 4 times between the 3 dots.

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
1

Slightly more complete than @Fabrício-Matté's above. It will catch any IP and will convert it to a specific domain name. This is useful especially if you're not sure which IP the user will use (e.g., when you have more than one IP such as internal and external IPs):

RewriteEngine on
RewriteCond %{HTTP_HOST} ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$
RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]
zstolar
  • 461
  • 1
  • 4
  • 9
0

If Apache receives a request where there are VirtualHosts it doesn't have an explicit ServerName or ServerAlias match for, it directs all those requests to the first VirtualHost that was defined.

I would set up a separate default virtual host and have all the "unmatched request" functionality in there.

Gareth
  • 133,157
  • 36
  • 148
  • 157