I want all nginx requests that aren't made by my IP address to be redirected to /some-page
. I'm currently using this nginx config:
if ($remote_addr != 127.0.0.1) {
rewrite ^ http://www.example.com/some-page;
}
This works for me as I'm not redirected, but anyone else is stuck in a redirect loop since the block doesn't check if the request is for /some-page
.
How can I fix this? I'm not sure how to check the request path.
Redirect HTTP to HTTPS version for Specified domain in Nginx Server_name domain-name.com www.domain-name.com – it specifies the domain names. So, replace it with your website domain name that you want to redirect. Return 301 https://domain-name.com$request_uri – it moves the traffic to the HTTPS version of the site.
Permanent redirects such as NGINX 301 Redirect simply makes the browser forget the old address entirely and prevents it from attempting to access that address anymore. These redirects are very useful if your content has been permanently moved to a new location, like when you change domain names or servers.
If this if
is created inside the location /
for example, create a separate location /some-page
this way the if
won't be executed when the URI is /some-page
/some-page
The problem is, when Bad IP is redirected to /some-page
it still redirects to /some-page
again because it's still a Bad IP, so it passes the if
test
My solution: Remove the /some-page
location from the /
block:
location / {
# bla bla
if ($remote_addr != 127.0.0.1) {
rewrite ^ http://www.example.com/some-page;
}
# rest of bla bla
}
location /some-page {
try_files index.html index.php; # or whatever
}
When Bad IP is forwarded to /some-page
it no longer will execute the if
condition, so that will end the infinite redirection loop.
location / {
error_page 403 = @badip
allow 127.0.0.1;
deny all;
#rest of bla bla
}
location @badip {
return 301 $scheme://example.com/some-page;
}
I ended up solving the issue by doing another if
check for the request path. I knew nginx doesn't support nested if
statements so I searched and found this blog post which provides a workaround -- updating a variable with each statement you want to check and then matching it in a final statement. In my case, I did this, which works:
if ($remote_addr != 127.0.0.1) {
set $check O;
}
if ($request_uri != "/some-page") {
set $check "${check}K";
}
if ($check = OK) {
rewrite ^ http://www.example.com/some-page;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With