I try to redirect all visit except from my own IP adress to a specific path/url (not file or directory just a route path)like "example.com/my-path" to home page. I have tried a several code in .htaccess file but nothing works.
I used this code:
RewriteCond %{REMOTE_ADDR} != 1.2.3.4 (MY IP)
RewriteRule /my-path https://example.com
Where I have wrong?
CodePudding user response:
RewriteCond %{REMOTE_ADDR} != 1.2.3.4 (MY IP) RewriteRule /my-path https://example.com
There's a few errors here:
There should be no space after
!=
and before the string you are testing.!=
is part of the CondPattern (2nd argument).=
is a prefix-operator (that makes it a string match, instead of a regex) and!
is an additional operator that negates the expression. So!=
is not one operator, but two stuck together.The
RewriteRule
pattern (ie./my-path
) is a regex that matches the requested URL-path. Note, however, that in a directory context (eg..htaccess
), the URL-path that is matched does not start with a slash.This will implicitly trigger a 302 (temporary) redirect. However, you should always be explicit and include the
R
flag.For external redirects you should nearly always include the
L
(last
) flag to prevent further processing.
The above should be written like this instead:
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !=1.2.3.4
RewriteRule ^my-path$ https://example.com/ [R=302,L]
This will match the requested URL /my-path
and issue a temporary redirect to https://example.com/
if the request is coming from an IP address that is not 1.2.3.4
.