【问题标题】:Making a clean URL with php arguments in it使用 php 参数创建一个干净的 URL
【发布时间】:2014-01-20 15:33:20
【问题描述】:

到目前为止,我已经使用 .htaccess 来删除“.php”扩展名,但这对我来说还不够。我希望 example.com/test?id=asdfjK 可以作为 example.com/asdfjK 访问。所以它只接受 URL 中的主要 php get 参数(我不知道该怎么称呼它们。

到目前为止,这是我的 .htaccess 文件:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_]+)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9_]+)/$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9_]+)$ /image.php?ID=$1
RewriteRule ^([a-zA-Z0-9_]+)/$ /image.php?ID=$1

【问题讨论】:

  • 现在有没有人知道如何做到这一点?我读过其他问题,但答案对我没有帮助。

标签: php .htaccess


【解决方案1】:

没有办法区分发送到index.php 的内容和发送到image.php 的内容。模式是相同的,这意味着所有内容都将与第一个匹配,并且没有任何内容会路由到image.php。您必须在 url 中添加一些内容,以便您可以匹配它。比如:

http://example.com/image/abcdefg123456

这意味着 htaccess 文件看起来像:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9]+)/?$ index.php?page=$1 [L,QSA]
RewriteRule ^image/([a-zA-Z0-9]+)/?$ image.php?page=$1 [L,QSA]

【讨论】:

  • 现在,当我进入我的域并使用 /image/sadfklj9(随机代码)时,Chrome 会加载一两秒钟,然后告诉我它运行重定向循环。
【解决方案2】:

问号后面的 PHP 参数称为“查询字符串”。

试试这样的:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteRule ^([a-zA-Z0-9]+)$ /index.php?page=$1 [L]

这应该重定向任何来自:

http://example.com/abc123

收件人:

http://example.com/index.php?page=abc123

另见:

【讨论】:

  • 那行不通:(。这些例子给了我与我之前对上述答案的评论相同的错误。
  • 我认为您可以通过在规则上方放置 RewriteCond 来绕过无限重定向。基本上,我认为因为规则匹配重写的输出,它会再次重写它(一次又一次,等等)。条件通过仅在尚未重写规则时应用规则来防止这种情况发生。请参阅上面的更新答案。
猜你喜欢
  • 1970-01-01
  • 2015-02-25
  • 2015-11-01
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
相关资源
最近更新 更多