【问题标题】:How to remove index.php and index from the URL using htaccess | PHP如何使用 htaccess 从 URL 中删除 index.php 和 index | PHP
【发布时间】:2022-05-07 21:21:39
【问题描述】:

我正在为 QA 论坛开发一个 PHP 网站。我的网站包含一个 qa 文件夹,例如 -

example.com/qa/ 在 qa 文件夹中,我有一个 index.php 文件。我正在从数据库中获取 QA 帖子,例如 -

example/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。

如何在不影响 qa 文件夹中其他页面的情况下从 URL 中删除索引。

【问题讨论】:

  • 从 RewriteRule 中删除 index/ 部分?!
  • @VishalRana,您能否发布前端网址,您希望从后端网址提供该网址以澄清问题。
  • @RavinderSingh13 现在,它运行良好。根据 brombeer,我已经从 RewriteRule 中删除了 index/。再次感谢您的贡献。

标签: php .htaccess


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 2015-01-20
    • 2023-03-07
    • 1970-01-01
    • 2011-05-20
    • 2017-03-15
    • 1970-01-01
    相关资源
    最近更新 更多