Score:4

use "rewrite" and "try_files" together [Nginx]

cn flag

I removed the ".php" suffix at the end of the PHP files on the Nginx server with the following code, but this time I cannot send some data to the server.

try_files $uri/ $uri.html $uri.php$is_args$query_string;

Some links on the site are sent with Ajax, and the ".php" extension is not available at the end of these links. E.g; https://panel.example.com/app/controller/ajax/collect

For example, when I want to access the "/collect" file that I want to access via Ajax or directly, I get the error "File not found". Because I do "rewrite" with the code below and provide a clean URL.

rewrite ^/([^/]+)/([^/]+)?$ /index.php?cmd=$1&scd=$2 last;
rewrite ^/([^/]+)/?$ /index.php?cmd=$1 last;

Sample link: https://panel.example.com/[details|cat|profile]/[subPages(productID, username..)]

As a result, the above codes are correct and working, but not working at the same time together. How can I run these two codes at the same time?

Full Nginx vHost File

Score:4
us flag

You could try following approach:

location ~ ^/(?<cmd>[^/]+)/(?<scd>[^/]+) {
    try_files /index.php?cmd=$cmd&scd=$scd =404;
}

location ~ ^/(?<cmd>[^/]+)/ {
    try_files /index.php?cmd=$cmd =404;
}

location / {
    try_files $uri/ $uri.html $uri.php$is_args$args;
}

We use nginx location matching algorithm here to first check matching of URL to regular expressions and then taking appropriate action for that URL.

I am using named captures here ?<cmd> to make variable names more clear.

Also, the ?$ part at end of regular expression is removed, since it makes no difference. Both ?$ and empty match any string.

Emre6 avatar
cn flag
Thank you for your help. Unfortunately I got a 404 Error but if I go to this address, I don't get any error; `https://panel.example.com/index?cmd=login` - [In order not to mislead you, full conf. I am sharing the content](https://pastebin.com/Uk4X8dqt)
djdomi avatar
za flag
no paste the config dont use a nopaste service
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.