Home > OS >  How to set auth_basic using condition?
How to set auth_basic using condition?

Time:10-16

I need to configure my Nginx site configuration to show a password only in my development server. Infact, I'm using CI/CD which deploy the app using Docker on production, but I don't need to show the password on production.

The development server usually end with a specific domain like: appname.example.com.

Is there a way to show the authentication only in development?

This is my configuration:

server {
    root   /var/www/html/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$args;

        auth_basic "Restricted Content";
        auth_basic_user_file /var/www/html/public/.htpasswd;
    }

    location ~ [^/]\.php(/|$) {

        fastcgi_split_path_info ^(. ?\.php)(/.*)$;

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;

        fastcgi_pass   php-upstream;
        fastcgi_index  index.php;
    }
}

Thanks in advance.

CodePudding user response:

You can use map block to get an auth_basic directive argument from the $host variable value:

map $host $realm {
    appname.example.com  "Resticted content";
    default              off;
}

server {
    root   /var/www/html/public;
    index index.php;

    auth_basic $realm;
    auth_basic_user_file /var/www/html/public/.htpasswd;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ [^/]\.php(/|$) {
        ...
    }
}

You can use regex expressions with the map directive using ~ modifier, for example

map $host $realm {
    ~appname\.example\.com$  "Resticted content";
    default                  off;
}
  • Related