【问题标题】:PHP Rewrite RulesPHP 重写规则
【发布时间】:2009-02-17 23:25:00
【问题描述】:

我的应用使用的实际 URL 是:

http://site.com/search.php?search=iPhone 

但我希望用

也能达到同样的效果
http://site.com/iPhone

我没有重写规则的经验,我该如何设置?

解决方案有效,但新 URL 显示在地址栏中。我认为可以进行设置,使其看起来好像页面位置是

http://site.com/iPhone

不改变显示

http://site.com/search.php?search=iPhone 

这可能吗?谢谢。

【问题讨论】:

    标签: .htaccess mod-rewrite


    【解决方案1】:

    在您网站的根目录中创建一个名为 .htaccess 的文件并将其放入其中。

    RewriteEngine on 
    Options +FollowSymlinks
    RewriteBase / 
    
    RewriteRule ^(.*) search.php?search=$1 [R]
    

    应该做的伎俩。

    不过,我建议你让它更具体一些,所以可能需要在你的 url 中使用搜索目录的用户。例如,使用 mysite.com/search/IPhone 代替 mysite.com/IPhone 会像

    RewriteEngine on 
    Options +FollowSymlinks
    RewriteBase / 
    
    RewriteRule ^search/(.*) search.php?search=$1 [R]
    

    这使得重定向正常页面变得更容易,例如关于我们或基本主页。

    正如 Chris 所说,执行此操作的不是 PHP,而是 Apache,它是否有效取决于您的托管设置。

    【讨论】:

      【解决方案2】:

      您需要在 .htaccess 文件中指定类似的内容:

      RewriteEngine on
      RewriteRule /(.*) /search.php?search=$1
      

      也检查一下:

      【讨论】:

      • 为什么你的正则表达式只尝试匹配数字?只是好奇,因为他的示例使用了“iPhone”,而不是数字。
      【解决方案3】:

      据我所知,重写规则不是 PHP 的一部分,而是 Apache(特别是 mod_rewrite)或您正在使用的任何服务器。对于 Apache,您需要在服务器上有一个名为 .htaccess 的文件,并在其中放入如下内容:

      RewriteEngine on
      RewriteRule ^(\w+)/?$ /index.php?search=$1
      

      ^(\w+)/?$ 是一个正则表达式 - 它匹配任何 1 个或多个字符的单词,然后可能是 /。所以它将site.com/iPhone 更改为site.com/index.php?search=iPhone。听起来对吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-16
        • 1970-01-01
        • 2011-10-22
        • 2014-04-30
        • 1970-01-01
        • 2011-02-13
        相关资源
        最近更新 更多