在htaccess中重写URL,移除问号并添加斜杠

5

我花了几个小时试图实现我认为很容易的事情。我有 http://localhost/testing_url_document/second.php?id=2,想将其转换为 http://localhost/testing_url_document/second/id/2。我已经成功去掉了php扩展名,但卡在了重写网站页面上。在htaccess文件中,我按照以下步骤进行操作。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

这是我的首页
索引.php
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        // put your code here
        ?>
        <a href="second/id/2">click here</a>
    </body>
</html>

Second.php

<?php 
 echo $_GET['id'];
?>

第二个php应该获取值2。
提前感谢您的帮助。
2个回答

3

请在/testing_url_document/.htaccess文件中添加以下内容:

RewriteEngine On
RewriteBase /testing_url_document/

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^./]+)(/.*)?$ $1.php$2 [L]

RewriteRule ^([\w-]+(?:\.php)?)/([\w-]+)/([\w-]+)/?$ $1?$2=$3 [L,QSA,NC]

正在处理 http://localhost/testing_url_document/second?id=2,但需要处理 http://localhost/testing_url_document/second/id/2。也就是说,当我们使用 $_REQUEST 参数获取 id 时,值为 2 的 id 没有被获取到。 - Harshit Sethi
当您输入 http://localhost/testing_url_document/second.php/id/2时会发生什么? - anubhava
对象未找到,服务器上未找到请求的URL。如果您手动输入了URL,请检查拼写并重试。 - Harshit Sethi
请展示你的完整/testing_url_document/.htaccess文件吗? - anubhava
让我们在聊天中继续这个讨论 - anubhava
显示剩余4条评论

0

这是可以解决您问题的最小配置:

RewriteEngine On
RewriteCond %{QUERY_STRING} ^site=(.*)$ [NC]
RewriteRule index.php /index/site/%1? [R=301,L]

1
好的...也许我在你的问题中漏掉了什么 :) 这个配置将 example.com/index.php?site=Page 地址重定向到 example.com/index/site/Page。它在 Apache/2.4.7 中运行得很好。 - alexeevdv
它可以工作,但我希望$_GET变量的输入与example.com/index/site/Page相同,即$_GET ['site'] = Page。 - Harshit Sethi
我们还可以通过 $_GET 获取站点的值。 - Harshit Sethi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接