We have Nginx and using it to serve a Laravel 8 project
I have the need to protect with a basic auth this demo project.
it works, using nginx and auth_basic_file directive
auth_basic "My DEMO";
location ~ ^/(api|public|images)/.* {
auth_basic off;
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
# Protect access
auth_basic_user_file /etc/nginx/auth/.htpasswd;
add_header X-Dovesono-php 1;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
I need to leave un protected entire block of /api/<some thing
Actually, using the above config, the browser ask me to authenticate at every ajax call to /api/. Also, even inserting right username and password, it will reask indefinitely
I resolved using this:
server {
....
auth_basic_user_file /etc/nginx/auth/.htpasswd;
location / {
auth_basic "My DEMO";
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
... ...
}
location /api/ {
auth_basic off;
try_files $uri /index.php?$query_string;
}
}
If first matches /api/
, no auth set up, and then causes the restart of parsing that will ending using location ~ \.php$
.
So page is served, but without asking http basic auth
For every other routes, it apply auth_basic and then causes the restart of parsing that will ending using location ~ \.php$
So page is served, but asking http basic auth