Score:0

nginx - Attempt to redirect path with variable internally fails

cm flag

i would like to redirect the request to a file from

/path/to/file/content?path=file.pdf

to

/new/path/to/file/file.pdf

under the same domain.

I tried simple rewrite rules or like this.

location ~ ^/path/to/file/content?path=(.*) {
   return 301 /new/path/to/file/$1;
}

Unfortunately, nginx does not understand the variable. What am I doing wrong? Does anyone have a tip for me, please? Unfortunately, I don't know much about reqex. Thanks a lot!

Score:0
gr flag

Unlike apache rewrite rules both location and rewrite nginx directives works with so-called normalized URI (see the location directive documentation to find out what does it mean) which does not include the query part. Check if the path query argument is not empty and do a redirect if the request URI matches your pattern using the following configuration fragment:

if ($arg_path) {
    rewrite ^/path/to/file/content /new/path/to/file/$arg_path? permanent;
}
Christian avatar
cm flag
Hello Ivan, thank you very much for your answer. I copied the fragment into the block location / { } But then nginx ignores this rule. But if I delete the if part, i.e. write only rewrite...., the redirection almost works. The browser then only says /new/path/to/file/, but the file name is missing.
Ivan Shatsky avatar
gr flag
Sorry, of course it is my typo, it should be `$arg_path` instead of `$arg_file`.
Christian avatar
cm flag
All is well, you help me a lot. Thank you very much. Now the if statement works. Unfortunately, the address in the browser still ends at /new/path/to/file/. The file name is missing.
Ivan Shatsky avatar
gr flag
The end user browsers usually cache permanent HTTP 301 redirects, so it can be cached URI from the previous configuration. Clear your browser cache or try from the incognito window.
Christian avatar
cm flag
Sorry, you're right, how stupid of me. You made my day, thank you very much!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.