php - 如何使用 htaccess 从 URL 中删除 index.php 和 index | PHP
问题描述
我正在为 QA 论坛开发一个 PHP 网站。我的网站包含一个 qa 文件夹,例如 -
example.com/qa/ 在 qa 文件夹中,我有一个 index.php 文件。我正在从数据库中获取 QA 帖子,例如 -
示例/qa/index/506/how-to-connect-the-html-page-to-the-mysql-database-using-php
我正在使用 htaccess 代码(htaccess 位于同一个 qa 文件夹中)-
RewriteEngine on
RewriteRule ^index/([0-9]+)/([0-9a-zA-Z_-]+)$ index.php?id=$1&slug=$2 [NC,L]
根据这个 htaccess 文件,我可以像打开 URL -
example/qa/index/506/how-to-connect-the-html-page-to-the-mysql-database-using-php
不是
example.com/qa/index.php?id=506&slug=how-to-connect-the-html-page-to-the-mysql-database-using-php
这运作良好,我喜欢它,但主要的事情从这里开始。
我想从 url 中删除索引
前
example/qa/index/506/how-to-connect-the-html-page-to-the-mysql-database-using-php
后
example/qa/506/how-to-connect-the-html-page-to-the-mysql-database-using-php
我在同一个 htaccess 文件中使用了这个代码
RewriteEngine On
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
但它不起作用。
还有一件事,我将在 qa 文件夹中创建更多页面,例如 - login.php、register.php。
如何从 URL 中删除索引而不影响 qa 文件夹中的其他页面。
解决方案
如何从 url 中删除索引
example.com/qa/index.php?id=506&slug=how-to-connect-the-html-page-to-the-mysql-database-using-php
至
example/qa/index/506/how-to-connect-the-html-page-to-the-mysql-database-using-php
前
只需在 index.php 所在的文件夹中创建一个 htaccess 文件。
RewriteEngine on
RewriteRule ^([0-9]+)/([0-9a-zA-Z_-]+)$ index.php?id=$1&slug=$2 [NC,L]
后
example/qa/506/how-to-connect-the-html-page-to-the-mysql-database-using-php
对于未来的访客来说,这将是更有价值的。如果您想从文件夹内的任何页面中删除 PHP (.php) 扩展名
前
example.com/qa/login.php
在 htaccess 文件上添加代码行之后
RewriteEngine On
RewriteRule ^login\/?$ login.php
现在,您可以像这样打开 URL -
example.com/qa/login
这是另一种使用 htaccess 文件从页面 URL 中删除 PHP 扩展 .php 的 htaccess 方法。
推荐阅读
- java - bean:define 的 JSTL 标记替换
- objective-c - Objective-C 代码中的解析错误
- laravel - Laravel cicle foreach 一个垃圾对象
- sql - 特定行之间的差异
- jackson - 杰克逊以 FAIL_ON_UNKNOWN_PROPERTIES 失败
- mapbox - Kepler.gl 地图中心默认设置为 0,0
- r - 如何根据高峰和非高峰时间在 R 中对我的图进行颜色编码?
- angular - Angular 6 ngFor 在切片管道之前计数
- javascript - 使用“async-await”模式时,Mocha 单元测试未完成
- go - 使用golang将输出字符串转换为映射