将目录中的所有url重定向到nginx中的单个php


Redirect all url in directory to single php in nginx

我想要一个php脚本来处理所有传入到我的/blog directoy的请求。php脚本检查url是否存在SQL记录(即www.example.com/blog/example_article)。如果找到记录,它将提供相应的页面数据。如果没有url的记录(即www.example.com/blog/nothing_here),则重定向到404。

我需要nginx中的重写规则。

我当前的配置:

    root /usr/share/nginx/html/example/;
    index index.php;
    server_name example.com www.example.com;
    location / {
            try_files $uri $uri/ @extensionless-php;
    }
    location /blog {
            rewrite ?; // here i need a rewrite rule
    }
    location /uploads {
            deny all;
    }
    error_page 404 /templates/404.php;
    location ~ '.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+'.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
            fastcgi_intercept_errors on;
    }
    location @extensionless-php {
            rewrite ^(.*)$ $1.php last;
    }

请注意,我使用的是无扩展URL。

答案:

location /blog {
    index article.php;
    rewrite ^/blog/(.*)$ /blog/article.php?slug=$1;
}