NGINX auth_basic exclude GET request to specific php script
I can't seem to figure out how to exclude a specific location from 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;
}
...
The location /sub/script.php needs free access. It would also be nice if it could only allow GET request to it. My problem seems to be the query parameters that come after it.
The script gets always requested with many query parameters script.php?param=something&other_param=somethingelse&etc=etc
Solution 1:
You current configuration is matching requests for /sub/script\.php$
on the following location
block:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
Use the following configuration which places the /sub/script\.php$
location above the \.php$
location because nginx
will stop evaluating at the first matched regex 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;
}
...