php - PHP 根据 REQUEST_URI 返回内容
问题描述
说,我的域是“www.miraj.com”。如果用户单击链接“www.miraj.com/childhood-of-miraj”,那么我想检查我的数据库是否有任何标题为“childhood-of-miraj”的帖子,否则应该显示 404 页面显示。但由于没有名为“childhood-of-miraj”的目录(文件夹),它立即返回 404 页。我怎样才能做到这一点?
解决方案
这取决于您使用的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 规则。
推荐阅读
- python - Keras 和 Scikit-learn 的加权准确度指标之间的差异
- java - 如何从 Date 变量和 int 变量计算新的 Date 值
- wordpress - 如何覆盖不在“模板”文件夹中的wordpress插件模板文件?
- java - 错误 -'javac' 不是内部或外部命令、可运行程序或批处理文件
- bash - 打印关键字前列中的最后一个数字
- javascript - 如何根据某些规则制作一个中间有空格的字符串
- clojurescript - 使用 Lein 更改 Figwheel 编译目录
- html - 使用 Angular 7 将 HTML(不渲染 HTML 页面)转换为 PDF
- java - 删除给定字符串中的数组字符串?
- javascript - 如果不满足三元运算符中的条件,是否可以写两个值