首页 > 解决方案 > PHP 根据 REQUEST_URI 返回内容

问题描述

说,我的域是“www.miraj.com”。如果用户单击链接“www.miraj.com/childhood-of-miraj”,那么我想检查我的数据库是否有任何标题为“childhood-of-miraj”的帖子,否则应该显示 404 页面显示。但由于没有名为“childhood-of-miraj”的目录(文件夹),它立即返回 404 页。我怎样才能做到这一点?

标签: php

解决方案


这取决于您使用的httpd (Apache 或 Nginx)。

对于Apache,您应该将 .htaccess 文件编辑为如下所示:

RewriteEngine On    # Turn on the rewriting engine 
RewriteRule    ^([A-Za-z-]+)/?$ FileToHandleDatabaseSearch.php?title=$1 [NC,L]

这将在服务器上将 URL 即时 www.miraj.com/childhood-of-miraj 转换为 www.miraj.com/FileToHandleDatabaseSearch.php?childhood-of-miraj,而不是在浏览器地址栏中。
FileToHandleDatabaseSearch.php

if (isset($_GET['title'])) {
    //...Search DB for $title
    //If title exists display page with title
    //If title does not exist display 404 page not found
}

对于NGINX,您在 conf 文件 www.miraj.com.conf中编辑它/etc/nginx/sites-available应该如下所示

server {
    listen 80;
    listen [::]:80;

    root /path/to/project/root;
    server_name www.miraj.com;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    rewrite ^([A-Za-z-]+)/?$ FileToHandleDatabaseSearch.php?title=$1 last;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    }

}

您可能希望为特定于对象的路径添加前缀以避免 URL 冲突。例如,如果childhood-of-miraj是电影标题,则重写条件为rewrite ^/movies/([A-Za-z-]+)/?$ "/path/to/project/root/FileToHandleDatabaseSearch.php?title=$1" last;

您可以访问Apache Rewrite Rules了解更多可以使用的.htaccess规则,并访问Nginx Rewrite Rules了解更多可以使用的 Nginx 规则。


推荐阅读