如何對一個位置停用 nginx basic_auth 但對網站的其餘部分啟用它

如何對一個位置停用 nginx basic_auth 但對網站的其餘部分啟用它

我正在嘗試停用特定目錄 ( /api/) 的 basic_auth,但對於我正在使用的網站的其餘部分仍然具有基本身份驗證。以下是我的nginx.conf

server {
    # base settings
    listen 80;
    server_name somesite-somewhere-anywhere.com;
    root /var/www/wordpress;
    index index.php index.html index.htm;

    if (!-e $request_filename) {

        rewrite ^(.+)$ /index.php?q=$1 last;
    }

    # setup logs
    access_log /var/log/nginx/somesite-somewhere-anywhere.com.access.log;
    error_log /var/log/nginx/somesite-somewhere-anywhere.com.error.log;

    # setup 404
    error_page 404 /404.html;
    location  /404.html {
        internal;
    }

    # map 403 to 404
    error_page 403 = 404;

    # hide wordpress details
    location ~ /(\.|wp-config.php|readme.html|licence.txt) {
        return 404;
    }

    # add trailing slash to wp-admin requests
    rewrite /wp-admin$ $scheme://$host$uri/ permanent;


    # ignore robots in logging
    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # ssl redirect

    # setup location
    location / {
        # setup basic auth 
        auth_basic dk; 
        auth_basic_user_file /var/www/htpasswd;

        # fastcgi setup
        location ~* (^(?!(?:(?!(php|inc)).)*/uploads/).*?(php)) {
            try_files $uri = 404;
            fastcgi_split_path_info ^(.+.php)(.*)$;
            fastcgi_pass unix:/var/run/php-fpm.socket;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            fastcgi_intercept_errors on;
            fastcgi_ignore_client_abort off;
            fastcgi_connect_timeout 60;
            fastcgi_send_timeout 180;
            fastcgi_read_timeout 180;
            fastcgi_buffer_size 128k;
            fastcgi_buffers 4 256k;
            fastcgi_busy_buffers_size 256k;
            fastcgi_temp_file_write_size 256k;
        }

        # prevent access to hidden files
        location ~ /\. {
            deny all;
            access_log off;
            log_not_found off;
        }
    }
    # allow access to api without auth
    location  /api/ { 
        auth_basic "off" ;
    }
}

答案1

你可以看到在nginx 驗證基本文檔“auth_basic 關閉;”就是你所需要的。所以我懷疑這裡還發生了其他事情。向我們展示您如何/如何存取該 URL?

也許您點擊的 /api 沒有尾部斜線?如果您仍然遇到問題,您可能可以透過以下方法解決它:

location /api/ {
    satisfy any;
    allow all;
    auth_basic           "dk";
    auth_basic_user_file "/var/www/htpasswd";
}

這是錯誤的方法,但根據在您的環境中做正確的事情的重要性,它可能會很快(如果您正確指定了位置/繼承)

相關內容