nginx+php 使用的时候经常需要伪静态,一般大家都手动设置。那有没有办法让 nginx 自动补全路径呢?
这两天折腾很久,才实现了这样一个功能:
请求 /a/b/c
若文件不存在,查找 /a/b/index.php,/c 作为 PATH_INFO;
若文件不存在,查找 /a/index.php,/b/c 作为 PATH_INFO;
若文件不存在,查找 /index.php,/a/b/c 作为 PATH_INFO;
若文件不存在,返回 404.

虽然这种损耗性能的行为不适合部署,但在本机调试的时候还是能够带来方便的 🙂

server 端应有如下代码,其他部分使用自己的配置:

index index.php index.html index.htm;

location / {
    set $path $request_uri;
    set $path_info "";

    try_files $uri $uri/ @404;
}

location @404 {
    if ($path ~ ^(.*)(/.+)$) {
        set $path $1/index.php;
        set $path_info $2;
        rewrite .* $path last;
    }
    return 404;
}

location ~ .+.php($|/) {
    fastcgi_split_path_info ^(.+.php)(/.+)$;
    if ($path_info !~ .*) {
        set $path_info $fastcgi_path_info;
    }
    try_files $fastcgi_script_name @404php;

    fastcgi_param PATH_INFO $path_info;

    fastcgi_index index.php;
    include fastcgi.conf;

    fastcgi_pass unix:/usr/local/var/run/php-fpm.sock;
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
}

location @404php {
    if ($path = /index.php) {
        return 404;
    }

    if ($path ~ ^(.*)(/.+)/index.php$) {
        set $path_info $2;
        set $path $1/index.php;
        rewrite .* $path last;
    }
    return 404;
}

results matching ""

    No results matching ""