使nginx相对于当前路径提供404文档

时间:2015-07-21 15:11:39

标签: nginx webserver

我有以下服务器块:

server {
    listen 80;
    server_name petpal.co.il;
    root /usr/share/nginx/petpal;
    index index.php;
    location / {
        try_files $uri $uri/ @extensionless-php;
    }
    location @extensionless-php {
        rewrite ^(.*)$ $1.php last;
    }
    location ~ \.php$ {
        try_files $uri /notfound;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

我需要做哪些修改才能使404文档根据用户当前所在的目录显示,例如在目录“/ en”中它将显示“/ en / notfound”和在目录“/”中它会显示“/ notfound”?

2 个答案:

答案 0 :(得分:0)

也许if会起作用?

set $lang "";
if ($uri ~ "^/en/") { set $lang "en/"; }
try_files $uri /${lang}notfound;

或者,如果您想要更通用的规则:

set $lang "";
if ($uri ~ "^/([a-z][a-z])/)") { set $lang "$1"; }
try_files $uri /${lang}notfound;

答案 1 :(得分:0)

感谢cnst的帮助,我设法解决了这个问题! 基本上我所要做的就是将这段代码放在php位置块之外:

set $lang "";
if ($uri ~ "^/en/") { set $lang "en/"; }
error_page 404 /${lang}notfound;

然后在php块内部执行:

try_files $uri =404;