Regex match the middle of a URL and also the ending?

Maxim Dounin mdounin at mdounin.ru
Sat Jun 3 17:16:07 UTC 2023


Hello!

On Sun, Jun 04, 2023 at 12:26:55AM +1000, Jore wrote:

> Hi all,
> 
> I have an app on a domain that is set by a developer to proxy at certain 
> URLs:
> 
> |example.com/browser/123foo0/stuff.js |
> 
> for example, where |123foo0| is some random key. The key may also change 
> length in future.
> 
> That’s all fine.
> 
> But I’d like to interrupt specific requests and not proxy them: I don’t 
> want to serve anything after the key that is in the path |/welcome| for 
> example, i.e. not proxy any of these:
> 
> |example.com/browser/123foo0/welcome/welcome.html 
> example.com/browser/foo456b/welcome/welcome.css 
> example.com/browser/bar123f/welcome/welcome.js 
> example.com/browser/456foob/welcome/other.stuff 
> example.com/browser/foo789b/welcome/ |
> 
> So I tried simple stuff first like: |location ^~ 
> /browser/.*/welcome/welcome.html {...|
> but couldn’t even get that working, before moving on to try capturing 
> groups like css files and scripts and so on.
> 
> I also tried putting regex in quotes, but that didn’t seem to work either.
> 
> What am I doing wrong?
> 
> Here’s a truncated version of the conf, with the location blocks only:
> 
> |location ^~ "/browser/.*/welcome/welcome.html" { return 200 'Not 
> proxied.\n'; add_header Content-Type text/plain; } location ^~ /browser 
> { proxy_pass http://127.0.0.1:1234; proxy_set_header Host $http_host; } 
> # landing page location / { root /var/www/foobar; index index.html; 
> try_files $uri $uri/ /index.html; } |

The "^~" location modifier is for prefix-match locations to 
prevent further checking of regular expressions, see 
http://nginx.org/r/location for details.  If you want to use a 
regular expression, you have to use the "~" modifier instead.

That is, proper configuration will look like:

location ~ ^/browser/.*/welcome/welcome.html$ {
    # URI matches given regular expression
    ...
}

location /browser/ {
    # URI starts with /browser/
    ...
}

location / {
    # anything else
    ...
}

Hope this helps.

-- 
Maxim Dounin
http://mdounin.ru/


More information about the nginx mailing list