Score:1

take the value from path in location and return it along with a string in nginx

ps flag

I am a newbie in the world of Nginx. While learning it, I am trying to accomplish this: I want to return a string whenever someone hits this URL: /greet/user and the string will be 'Hello user.' So, if someone hits localhost/greet/john, the page will show this string: 'Hello john'; if the URL is localhost/greet/merry, the string will be 'Hello merry.'

I tried doing that with the following code fragment. To note, I did use a regular expression to catch any argument that came second.

location ~/greet/(user+) {
    set $user user;
    return 200 'Hello ${user}';
}

What am I missing here? And how should it be done? My OS is Ubuntu 22.04. This is my first post on server fault, and I am new to the world of web servers. So, if I miss out on anything while writing this post, I hope I will not receive any penalty.

in flag
That "regular expression" is nonsense. You are capturing the character sequence `use` followed by one or more `r`.
lone wolf avatar
ps flag
@GeraldSchneider, then how should it be done?
Score:0
ps flag

I have figured it out. What I did wrong was in the regular expression. It was capturing any number of 'r's followed by use.

So the correct code was the following:

location ~ /greet/(\w+) {
    set $user $1;
    return 200 'Hello ${user}';
}

I set the first word to a variable named user and returned it with a string.

Score:0
pl flag

You could also use sub_filter to replace HTML or send your response in a header.

Nikita Kipriyanov avatar
za flag
How does this relate to a question?
I sit in a Tesla and translated this thread with Ai:

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.