Nginx Basic Auth Dengan Pengecualian

20 Januari 2021 • 1 menit untuk membaca artikel ini

Aku ada aplikasi yang dibuat pakai Laravel. Dari aplikasi itu mau dipasangin basic auth dengan pengecualian. Maksudnya ada beberapa part yang tidak ingin dipakaikan basic auth.

Misalnya gini:

  • Basic auth off jika diakses pakai ip tertentu..
  • Basic auth off jika request uri /?webhook-author=sumar¬ification-target=telegram
  • Jika tidak memenuhi kondisi diatas, maka basic auth on.

Untuk mencapai tujuan diatas, ada banyak cara. Aku memilih pakai Module ngx_http_map_module dan Module ngx_http_geo_module karena menurutku lebih mudah dan fleksible.

Sehingga, config vhost nginx-nya menjadi:

geo $auth {
     default "Restricted Area";
     172.16.1.0/24 "off";
     192.168.1.0/24 "off";
}


map $request_uri $auth {
     default "Restricted Area";
     "/?webhook-author=sumar&notification-target=telegram" "off";
}

server {
    server_name devel.internal-site.localdomain;

    root /var/www/devel.internal-site.localdomain;
    index index.php;

    access_log /var/log/nginx/devel.internal-site.localdomain-access.log;
    error_log /var/log/nginx/devel.internal-site.localdomain-error.log;

    location / {
      try_files $uri $uri/ /index.php?$args;
      
      # basic auth on/off based on nginx map module
      auth_basic $auth;
      auth_basic_user_file "/etc/nginx/myhtpasswd";
    }

    location ~ \.php$ {
      include snippets/fastcgi-php.conf;
      fastcgi_pass    unix:/var/run/php/php7.4-fpm.sock;
      fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }


    listen 443 ssl http2; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/devel.internal-site.localdomain/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/devel.internal-site.localdomain/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

server {
    if ($host = devel.internal-site.localdomain) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    server_name devel.internal-site.localdomain;
    return 404; # managed by Certbot
}

Done

Techlinuxnginx

Sumarsono

System Administrator
Kembali ke atas

Freebsd Check Listening Port>>

<<Nginx Return Custom Json