regex - 如何使正则表达式 nginx 位置起作用?

标签 regex nginx

我的 nginx 配置中有以下位置:

server {
    listen       80;
    server_name  localhost;

    location ~ ^/(?!api)(.*)/api {
        alias /var/www/api/$1;
    }

    location /api {
        alias /var/www/api/latest;
    }

我试图将/api 匹配为最新版本,将//api 匹配为其他版本。非正则表达式位置工作正常,但我在其他位置收到 403。

我认为这与所提供的文件和权限没有任何关系,因为如果我尝试访问,我会收到 403

/latest/api

即使这些文件与提供的文件相同

/api

有人知道我为什么会收到 403 吗?

nginx 错误是:

directory index of "/var/www/api/latest" is forbidden, client:
172.17.0.1, server: localhost, request: "HEAD /latest/api/ HTTP/1.1",
host: "localhost"

最佳答案

问题不在于正则表达式,而在于正则表达式 location 中使用 alias 指令。请参阅this document了解更多。

在相关说明中,您应该在前缀 location 上使用 ^~ 修饰符,而不是使用否定先行断言。请参阅this document了解更多。

例如:

location ~ ^(/[^/]+)/api(.*)$ {
    alias /var/www/api$1$2;
}

location ^~ /api {
    alias /var/www/api/latest;
}

关于regex - 如何使正则表达式 nginx 位置起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42681463/

相关文章:

ios - AFNetworking 2.0 和 Nginx 之间的文件缓存

php - 使用 SSL 的 nginx 反向代理背后的 Docker 上的 Wordpress

docker - 我应该为我的Web应用程序的一部分创建多个Dockerfile吗?

java - Regex java 一个用于提取第一个字母字符的正则表达式

双花括号的 Java 正则表达式模式

javascript - Node.js semver 中的正则表达式非捕获组

javascript - 正则表达式不正确匹配 - javascript

Django url 在 nginx 代理后面带有 https

python - 为什么我有错误 "Address already in use"?

asp.net - SWIFT 代码的正确正则表达式是什么?