Home > Software engineering >  disallow direct access to nginx location
disallow direct access to nginx location

Time:05-04

I have two locations in nginx, where one redirect to another. I want to make next:

First one allow direct access in browser and redirect query to second location. Second location transform get to post, make proxy query and allowed only from first location.

First:

location /first/ {
         rewrite ^ /second/ permanent;
}

Second:

location /second/ {

proxy_method POST;
proxy_set_body '{ "arg1": "$arg_arg1", "arg2": "$arg_arg2" }
proxy_pass https://some_api.com/

}

How could I check in second location if it redirected from first one (not direct access in browser) and show some 40x error if it was direct access?

Trying to use internal directive, but this rewrite does not fall into the category of internal redirects.

Redirect using to hide /first/ url in user browser

Thanx in advance

CodePudding user response:

This is not about nginx, rather about HTTP protocol and user browser behavior. Whatever you are trying to do, I think you are trying to do it in a wrong way. Generally, you need to generate some one-time token at your first location and use it at the second one, but this is a web app job, nginx is just a web server and not a web framework (however it can be possible using third party modules like lua-nginx-module). If you want to do it using nginx itself, no matter what solution you'll finished up with, it will be possible to trace and spoof it.

Here is an idea in general:

location /first/ {
    # set cookie with an access token
    add_header Set-Cookie "my_token=my_super_password; path=/second/" always;
    # do not use 301 redirect here or it will be cached by user browser, use 302 only!
    rewrite ^ /second/ redirect;
}
location /second/ {
    if ($cookie_my_token != "my_super_password") { return 403; }
    # clear the token cookie on response
    add_header Set-Cookie "my_token=deleted; path=/second/; expires=Thu, 01 Jan 1970 00:00:00 GMT" always;
    ... rest of configuration here
}
  • Related