![仅在 HTTP GET 请求中将位置块应用于别名请求](https://linux22.com/image/716274/%E4%BB%85%E5%9C%A8%20HTTP%20GET%20%E8%AF%B7%E6%B1%82%E4%B8%AD%E5%B0%86%E4%BD%8D%E7%BD%AE%E5%9D%97%E5%BA%94%E7%94%A8%E4%BA%8E%E5%88%AB%E5%90%8D%E8%AF%B7%E6%B1%82.png)
我有一个通过 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;
}