我有一個 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
}
例如,每當我嘗試時curl foo.example.com/bill/540/verify,它都會回傳404 not found。
我使用以下鏈接來創建上述配置:
- “proxy_pass”不能在正則運算式給出的位置包含 URI 部分
- Nginx 只允許對某些 URL 的 POST 請求
- https://nginx.org/en/docs/http/ngx_http_core_module.html#limit_except
問題:知道如何實作這一目標嗎?
任何幫助表示贊賞,在此先感謝。
uj5u.com熱心網友回復:
好的,我想通了:
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
}
訣竅是捕獲我想要的部分,然后將它們作為變數傳遞,例如$1, $2, ...在rewrite部分中。
我在 PCRE 風格中使用了This regex builder,因為它在 Nginx 檔案中被提及,以確保我的 regex 是正確的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/515782.html
