Nginx rewrite rule subfolder 404 error

I cannot figure out how should I setup my index.php file with Nginx rewrite rules that it will work like example below.

If I visit the url it gives me 404 error not found instad echo 'hello'.

URL:

http://www.example.com/directory/sub-directory/

/sub-directory/ from given URL actually is not real directory inside /directory/. If I visit the URL, i got 404 error - which is real ok, but /sub-directory/ is friendly URL (without query ?argument=value).

/sub-directory/ is not fixed value (in this example below it is), it can be /sub-directory-new/ - depends.

So, for any value within /value/ after /directory/ in URL, how could I not get 404 error if I visit that kind of URL?

Index.php in /directory/:

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$wanted = "sub-directory";

$tokens = explode('/', $actual_link);
$result =  $tokens[sizeof($tokens)-2]; // result is "sub-directory"
if($wanted == $result) {
    echo "hello";
}

Nginx:

location /directory {
    try_files $uri $uri/ /directory/$uri;
    error_page 404 =200 /directory
}

Should I add some arguments for the rule, like: location /directory$1? If so, which one and how to get it working?

Anyone got some ideas?

Thanks for sharing and info!

2
задан 1 April 2016 в 01:35
1 ответ

Обычный способ создания дружественных URL-адресов в nginx выглядит следующим образом:

location /directory {
    try_files $uri $uri/ @rewrites;
}

location @rewrites {
    rewrite ^ /directory/index.php;
}

Эта конфигурация предполагает, что ваша директива root указывает на каталог, в котором находится / directory .

Итак, здесь nginx сначала попытается, если файл или каталог существует в реальной файловой системе. Если файл не существует, он перенаправляет запрос в ваш файл PHP. Естественно, вам необходимо правильно настроить блок обработки PHP в nginx.

2
ответ дан 3 December 2019 в 11:33

Теги

Похожие вопросы