【问题标题】:htaccess rewrite from page ID to name not workinghtaccess 从页面 ID 重写为名称不起作用
【发布时间】:2015-11-04 05:07:55
【问题描述】:

我正在使用 index.php 上的表单中的 GET 方法调用?page=about(即,'about' 是一个选择选项)。单击提交后,URL 将如下所示:

http://example.com/?page=about

但是我希望它看起来像这样:

http://example.com/about

但要让脚本 (PHP) 在 index.php 上运行(不要也不希望有一个“关于”文件),即。发送表单后,我想在同一页面上使用 GET 值。我可以让php脚本工作,它反应很好,但是URL重写根本不起作用。

我已经尝试了下面的htaccess重写,但它没有做任何事情,URL仍然如上。

我的 htaccess:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ?page=$1 [L,QSA]

非常感谢您的帮助,因为我不知道为什么这不起作用。我在网上搜索过,每个人都指向这个规则,但它对我没有任何作用。

提前非常感谢!

编辑:

让我发布我使用的 php 代码,对不起,我错过了。我现在已经删除了 action 属性,因为我在浏览器中使用它,我知道在提交表单时会将我发送到相同的位置:

<?php

$page = $_GET['page'];

switch($page){
 case 'about': echo 'I am me'; break;
 case 'galery': echo 'Nice pictures here'; break;
}

?>

<body>

<form action="/" method="get">
<select name="page">
    <option value="about">about</option>
    <option value="galery">galery</option>
</select>
<input type="submit" value="Submit" />
</form>
</body>

编辑 #2:

我必须将action="/" 添加到表单标签中才能使anubhava 的解决方案起作用。

【问题讨论】:

  • ?page=$1更改为index.php?page=$1
  • 谢谢,但这并没有改变任何事情,很遗憾
  • mod_rewrite 是否启用?没有什么其他应该是错的。该错误与您当时发布的任何内容无关。 =/
  • 我正在使用anabhava的解决方案和上面的php代码here - 这是一个godaddy共享主机,我过去使用htaccess成功
  • 使用您拥有的链接,确保您删除 RewriteBase 并进行测试。

标签: php forms .htaccess mod-rewrite get


【解决方案1】:

这应该是您完整的 .htaccess:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

#external redirect from /?page=about OR /index.php?page=about to /about
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(?:index\.php|)\?page=([^\s]+) [NC]
RewriteRule ^ /%1? [R=301,L]

#internal forward from /about to /?page=about
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+?)/?$ /?page=$1 [L,QSA]

【讨论】:

  • 非常感谢,这看起来确实像我要找的东西,但不幸的是它没有改变任何东西,我的 URL 仍然是 http://domain.com/?page=about :( - 现在添加了我的 PHP 代码;我可能会做错事了……
  • 您的问题已关闭,建议您创建一个新问题,其中包含所有详细信息和指向此问题的链接,以便我们更好地回答。
  • 它现已重新开放,所有详细信息均可用。如果您需要更多,请告诉我!
  • 请确保 mod_rewrite 和 .htaccess 已启用。还要确保上面的 .htaccess 在 $DOCUMENT_ROOT 目录中。
  • 我正在使用你的解决方案和上面的 php 代码here - 这是一个 godaddy 共享主机,我过去使用 htaccess 成功
【解决方案2】:

试试

 ...
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]

还有

我在 index.php 的表单中使用 GET 方法调用 ?page=about

尝试调用正确的链接? '/about' 而不是 '?page=about'

【讨论】:

  • 如果您要回答,至少使用 OP 想要的相同变量名。 =P
  • @Jon 以为我改了 xD
猜你喜欢
  • 1970-01-01
  • 2021-06-29
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
相关资源
最近更新 更多