Dav*_*ojo 1 php nginx basic-authentication symfony
我在 nginx 服务器下有一个 symfony 应用程序。我想启用基本的 http 身份验证,但排除 /api/ url 请求中的所有内容。
这是我当前的 nginx 配置:
server {
listen 80;
listen [::]:80;
root /home/mysite/www/web;
index app.php index.php index.html;
server_name mysite.com;
error_log /home/mysite/logs/error.log warn;
access_log /home/mysite/logs/access.log;
location / {
# try to serve file directly, fallback to app.php
try_files $uri /app.php$is_args$args;
}
# PROD
location ~ ^/app\.php(/|$) {
include /etc/nginx/php-mysite.conf;
# Protect access
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location ~ ^/app\.php/api/(.*) {
include /etc/nginx/php-mysite.conf;
auth_basic "off";
}
location ~ /\.ht {
deny all;
}
}
Run Code Online (Sandbox Code Playgroud)
其中/etc/nginx/php-mysite.conf是 php-fpm 配置。效果很好。
问题在于,似乎每个请求都由^app.php(/|$)location 指令处理。我无法将其配置为在访问/api/...url 时禁用身份验证请求。
我花了几个小时没有成功。
嗯,我不喜欢这个解决方案,但它确实有效。我所做的是检查 location 指令中的 request_uri,如果它以 /api 开头,那么我启用 auth basic。我想为此目的使用两个单独的位置,而不是在该位置内使用 if 。
这是位置指令,默认情况下它是启用的,如果请求匹配 ^/api/.*$ 则身份验证设置为关闭:
# PROD
location ~ ^/app\.php(/|$) {
include /etc/nginx/php-mysite.conf;
# Protect access
set $auth "Restricted";
if ($request_uri ~ ^/api/.*$){
set $auth "off";
}
auth_basic $auth;
auth_basic_user_file /etc/nginx/.htpasswd;
}
Run Code Online (Sandbox Code Playgroud)