简体   繁体   中英

How to whitelist remote ip addresses in nginx behind a load balancer Laravel

I have a list of IP addresses I want to allow on my server via nginx behind a load balancer. I'm currently migrating from apache to nginx and my previous set up in apache was like this:

    RewriteBase /
    RewriteCond %{REMOTE_HOST} !^123.456.123.789
    RewriteCond %{REMOTE_HOST} !^456.123.789.123
    RewriteCond %{REMOTE_HOST} !^123.567.456.789
    RewriteCond %{REMOTE_HOST} !^123.456.789.100
    RewriteCond %{REMOTE_HOST} !^127.0.0.1
    RewriteCond %{REQUEST_URI} !/maintenance.php$ [NC]
    RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif|css|js|api) [NC]
    RewriteRule .* /maintenance.php [R=302,L]

I would like to apply a similar approach in nginx by redirecting all requests except a list of ip addresses.


location / { 


    if ($remote_host !~ "^123.456.123.789"){
        rewrite ^(.*)$ /maintenance.php redirect;
    }
    if ($remote_host !~ "^456.123.789.123"){
        rewrite ^(.*)$ /maintenance.php redirect;
    }
    if ($remote_host !~ "^123.567.456.789"){
        rewrite ^(.*)$ /maintenance.php redirect;
    }
    if ($remote_host !~ "^123.456.789.100"){
        rewrite ^(.*)$ /maintenance.php redirect;
    }
    if ($remote_host !~ "^127.0.0.1"){
        rewrite ^(.*)$ /maintenance.php redirect;
    }


    try_files $uri $uri/ /index.php?$query_string;
    gzip_static on;
}

You mean, all requests except a list of whitelisted IPs and static resources as your .htaccess did? Try this:

map $uri $checkip {
    /maintenance.php                "-";
    ~\.(jpe?g?|png|gif|css|js|api)  "-";
}

map $checkip$remote_addr $stop {
    ~^-              "";
    123.456.123.789  "";
    456.123.789.123  "";
    123.567.456.789  "";
    123.456.789.100  "";
    127.0.0.1        "";
    default          1;
}

server {
    ...
    if ($stop) {
        return 302 /maintenance.php;
    }
    # your locations here
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM