大网数据广告活动
服务器运维问答

Nginx rewrite rule subfolder 404 error

· 52CE 我爱测

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…

问题原文

原帖链接 · Ho Thanh Cyberdelia Nhan · CC BY-SA 3.0

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!

已采纳解答

原帖链接 · Tero Kilkanen · CC BY-SA 3.0

The usual way of doing friendly URLs in nginx is like this:

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

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

This configuration assumes that your root directive points to the directory where /directory is located.

So, here nginx will try first if the file or directory exists in the real filesystem. If the file does not exist, then it forwards the request to your PHP file. Naturally you need to have your PHP processing block correctly configured in nginx.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-03-31)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。