我有一个通过 nginx 访问的 Web 应用程序,它充当反向代理。但是,此应用程序的子路径别名为目录。服务器配置如下:
server {
# ...
location /myapp/files {
alias /var/www/myapp/files;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
}
location /myapp/ {
proxy_pass http://127.0.0.1:3000/;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
}
}
上述设置将所有请求都设置为 ,/myapp/files
无论请求方法是什么。有没有办法只将 GET 请求设置为/myapp/files
,并将 DELETE 方法代理到 Web 应用程序?
限制如果防止写出如下内容:
if ($request_method = "GET") {
location /myapp/files {
alias /var/www/myapp/files;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
}
}
正如评论中所建议的,尝试做类似的事情这使用我的配置:
location /myapp/files {
auth_basic Restricted;
auth_basic_user_file /etc/nginx/htpasswd;
if ($request_method = "GET") {
alias /var/www/myapp/files;
}
if ($request_method = "DELETE") {
proxy_pass http://127.0.0.1:3000/;
}
}
}
结果是:
nginx: [emerg] "alias" directive is not allowed here in /etc/nginx/sites-enabled/default:44
我怎样才能实现这个目标?
答案1
尝试使用一系列内部重写(未经测试,直接在浏览器中编写):
location /myapp/files {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/htpasswd;
rewrite ^(/myapp/files)(.*) $1.$request_method$2 break;
}
location /myapp/files.GET {
alias /var/www/myapp/files;
internal;
}
location /myapp/files.DELETE {
rewrite ^/myapp(/files)(.*) $1$2 break;
proxy_pass http://127.0.0.1:3000/;
internal;
}