[英]Nginx - How to serve a static file to a particular user agent?
I am trying to restrict access to a particular json file for a certain user-agent using the configuration files in Nginx.我正在尝试使用 Nginx 中的配置文件限制对某个用户代理的特定 json 文件的访问。
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
try_files $uri$args $uri$args/ /index.html;
}
location /v1/ {
proxy_pass http://127.0.0.1:8118;
proxy_pass_header Server;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location = /v1/apischema {
root /usr/share/nginx/json;
if ($http_user_agent ~ useragentname) {
try_files /openapi.json;
break;
}
}
} }
The idea is to restrict access to openapi.json for an internal user.这个想法是限制内部用户对 openapi.json 的访问。
Please let me know where I am going wrong.请让我知道我哪里出错了。
try_files
can be used in a server
or location
block. try_files
可用于server
或location
块。 See Context: in this document .请参阅上下文:在本文档中。
There are a number of ways to achieve this.有多种方法可以实现这一点。
Using if
:使用
if
:
location = /v1/apischema {
if ($http_user_agent ~ useragentname) {
rewrite ^ /openapi.json last;
}
}
location = /openapi.json {
internal;
root /usr/share/nginx/json;
}
The internal
directive prevents this URI being accessed directly. internal
指令可防止直接访问此 URI。 See this caution on the use of if
.请参阅有关使用
if
注意事项。
Or using map
with try_files
:或者使用带有
try_files
map
:
map $http_user_agent $apischema {
~useragentname /openapi.json;
default /nonexistant;
}
server {
...
location = /v1/apischema {
root /usr/share/nginx/json;
try_files $apischema =404;
}
}
See this document for details.有关详细信息,请参阅此文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.