Score:2

nginx: How to write regex to split URL into host and "everything else"?

I want to map

https://www.example.com/Something/SomethingElse/

to

https://www.example.com/index.php?/Something/SomethingElse/

So far I understood that I need the location directive in nginx and use the try_files inside, something like this:

location ~ *???* {
  try_files $uri $uri/ /index.php?$1;
}

Now, the question is: how do I write the regular expression *???* to split URL, so I get the /Something/SomethingElse/ back (into $1)? Is it possible?

Perhaps, there is an easier way? nginx variable?

sv flag
Welcome to ServerFault. You may use `request_uri` that contains "everything else" (excluding the host). Ref: https://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_uri .
Александр Кулагин avatar
@PothiKalimuthu Perhaps I am doing something wrong, but using `$request_uri` results in "rewrite or internal redirection cycle while internally redirecting to "/index.php"". How do I write it properly?
sv flag
`location / { try_files $uri $uri/ /index.php?$request_uri`. Please post your full configuration to understand the redirection issue better.
Александр Кулагин avatar
@PothiKalimuthu Can you post this as answer, so I can accept it?
sv flag
Sorry about the delay. I wasn't available lately. Posted my reply as an answer. Thanks.
Score:1
sv flag

The variable $request_uri that contains all parts of URL excluding the host (and the scheme - http or https). So, the solution is to use the following code (or something similar)...

location / {
   try_files $uri $uri/ /index.php?$request_uri
}

We have a similar variable in Nginx named $uri. It is not recommended to use it as it can change its value during the run time.

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.