NGINX auth_basic 排除对特定 php 脚本的 GET 请求

NGINX auth_basic 排除对特定 php 脚本的 GET 请求

我似乎无法弄清楚如何从 auth_basic 中排除特定位置。

server {
        server_name example.com;

        root /var/www/html;

        index index.php;

        auth_basic "Nein nein nein";
        auth_basic_user_file .htpasswd;

        location / {
                try_files $uri $uri/ =404;
        }

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

        # this script needs free access and takes query string parameters
        location /sub/script.php {
                auth_basic off;
        }

        # this works fine
        location /sub/a-javascript.js {
                auth_basic off;
        }
...

/sub/script.php 位置需要自由访问。如果它只允许对其发出 GET 请求,那就太好了。我的问题似乎是它后面的查询参数。

该脚本总是被要求使用许多查询参数 script.php?param=something&other_param=somethingelse&etc=etc

答案1

您当前的配置符合/sub/script\.php$以下location区块的请求:

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

使用以下配置,将/sub/script\.php$位置置于位置之上,\.php$因为nginx将在第一个匹配的正则表达式处停止评估location

server {
        server_name example.com;

        root /var/www/html;

        index index.php;

        auth_basic "Nein nein nein";
        auth_basic_user_file .htpasswd;

        location / {
                try_files $uri $uri/ =404;
        }

        location ~ /sub/script\.php$ {
                auth_basic off;
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
                limit_except GET { deny all; } # Also allows HEAD
                }

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

        # this works fine
        location /sub/a-javascript.js {
                auth_basic off;
        }
...

相关内容