首页 > 解决方案 > 如何使用 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 文件夹中的其他页面。

标签: php.htaccessqa

解决方案


如何从 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 方法。


推荐阅读