如何在Nginx中允许包含正则表达式/通配符的特定URL的特定方法?

r7s23pms  于 2022-11-02  发布在  Nginx
关注(0)|答案(1)|浏览(195)

我有一个Nginx,我需要允许访问特定URL的特定方法,更重要的是,这些URL包含正则表达式。
具体要求如下:

/bill/<SOME_NUMBER_THAT_CHANGES>/verify --> GET & POST only

/bill/ipn/<SOME_STRING_THAT_CHANGES> --> POST only

我目前无法使用的配置如下:

server {
    server_name             foo.example.com;

    location ~ ^/bill/([0-9]+)/verify { 
        limit_except GET POST {
           deny all;
        }
        proxy_pass http://app:<PORT>/$1;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location ~ ^/bill/ipn/([A-Za-z0-9]+) { 
        limit_except POST {
           deny all;
        }
        proxy_pass http://app:<PORT>/$1;
        proxy_set_header X-Real-IP $remote_addr;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/foo.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/foo.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

例如,每当我尝试curlfoo.example.com/bill/540/verify时,它都会返回404 not found
我已经使用以下链接创建了上述配置:

问:你知道如何实现这一点吗?
任何帮助都是感激不尽的,提前表示感谢。

aurhwmvo

aurhwmvo1#

好吧,我想明白了:

server {
    server_name             foo.example.com;

    location ~ ([0-9]+)\/verify(\?status=.*)* {
        rewrite ([0-9]+)\/verify(\?status=.*)* /bill/$1/verify$2 break;
        proxy_pass http://app:<PORT>;
        proxy_set_header X-Real-IP $remote_addr;

        limit_except GET POST {
           deny all;
        }
    }

    location /bill/ipn {
        limit_except POST {
           deny all;
        }
        proxy_pass http://app:<PORT>;
        proxy_set_header X-Real-IP $remote_addr;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/foo.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/foo.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

技巧是捕获我想要的部分,然后将它们作为变量传递,例如rewrite部分中的$1, $2, ...
我在PCRE风格中使用了This regex builder,因为Nginx文档中提到了它,以确保我的regex是正确的。

相关问题