简体   繁体   中英

Nginx and auth_basic with cgit

On an Arch Linux server running Nginx, I setup correctly cgit. I want to protect cgit with a basic authentication password, except for one directory /pub/ . As seen on the documentation , I thought about put on the server context an authentication, and get an exception with the location context for the /pub/ directory. I tried this link to get the path correctly.

Here the configuration file of nginx of the corresponding part.

server {
    listen       80;
    server_name  git.nicosphere.net;
    index cgit.cgi;
    gzip off;

    auth_basic "Restricted";
    auth_basic_user_file /srv/gitosis/.htpasswd;

    location / {
        root /usr/share/webapps/cgit/;
    }

    location ^~ /pub/  {
        auth_basic off;
    }

    if (!-f $request_filename) {
       rewrite ^/([^?/]+/[^?]*)?(?:\?(.*))?$ /cgit.cgi?url=$1&$2 last;
    }

    location ~ \.cgi$ {
        gzip off;
        include fastcgi_params;
        fastcgi_pass    127.0.0.1:9001;
        fastcgi_index   cgit.cgi;
        fastcgi_param   SCRIPT_FILENAME /usr/share/webapps/cgit/cgit.cgi;
        fastcgi_param   DOCUMENT_ROOT /usr/share/webapps/cgit/;
    }
}

This ask me for authentication for whatever any url are. For some easier tests, I tried to leave root without authentication, and only /pub/ with authentication. In this case, it doesn't ask for password at all. So far, I managed to protect either everything or nothing.

Thanks for your help, and my apologies for my approximative English.

I think you want something like this:

server {
    listen       80;
    server_name  git.nicosphere.net;
    index cgit.cgi;
    gzip off;

    root /usr/share/webapps/cgit;

    # $document_root is now set properly, and you don't need to override it
    include fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME $document_root/cgit.cgi;

    location / {
        try_files $uri @cgit;
    }

    # Require auth for requests sent to cgit that originated in location /    
    location @cgit {
        auth_basic "Restricted";
        auth_basic_user_file /srv/gitosis/.htpasswd;

        gzip off;
        # rewrites in nginx don't match the query string
        rewrite ^/([^/]+/.*)?$ /cgit.cgi?url=$1 break;
        fastcgi_pass    127.0.0.1:9001;
    }

    location ^~ /pub/  {
        gzip off;
        rewrite ^/([^/]+/.*)?$ /cgit.cgi?url=$1 break;
        fastcgi_pass    127.0.0.1:9001;
    }
}

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