【问题标题】:how to write mod_rewrite rule in .htaccess如何在 .htaccess 中编写 mod_rewrite 规则
【发布时间】:2016-02-25 17:13:45
【问题描述】:

我正在使用 htaccess 文件中的 mod_rewrite 将一些 url 重定向到特定页面。该项目是在核心 PHP(无框架)中开发的,我正在使用 xampp 服务器,

例如:我希望将以下 url 重定向到 test.php

localhost/project/any_string //should be redirected to test.php
localhost/project/any_string/test //should be redirected to new_test.php

localhost/project/any_string.php //should be redirected to any_string.php only
localhost/project/any_string/any_string.php //should be redirected to any_string/any_string.php only

我启用了 mod_rewrite,任何帮助将不胜感激。

【问题讨论】:

  • 'RewriteRule ^([a-z0-9_\-]+) test.php [L,NC]'

标签: php apache .htaccess redirect mod-rewrite


【解决方案1】:

如果我了解您的需要,就可以这样做:

RewriteEngine On
RewriteRule ^(.*)project/(.*)/(.*).php$ /$2/$3.php [L,R=301]
RewriteRule ^(.*)project/(.*).php$ /$2.php [L,R=301]
RewriteRule ^(.*)project/(.*)test$ /new_test.php [L,R=301]
RewriteRule ^(.*)project/(.*)$ /test.php [L,R=301]

顺便说一下,这里的规则顺序很重要,一定要保持完全一致。

【讨论】:

    【解决方案2】:

    您是否正在寻找类似以下的内容?

    RewriteEngine On
    RewriteRule localhost/project/(.*)/test new_test.php [R]
    RewriteRule localhost/project/(.*) test.php [R]
    RewriteRule localhost/project/(.*)/(.*).php $1/$2.php [R]
    RewriteRule localhost/project/(.*).php $1.php [R]
    

    [R] 标志强制重定向。 请注意,较长的匹配列在较短的匹配之前(否则永远不会匹配较长的匹配。)

    【讨论】:

    • 我已经尝试过您的解决方案,但它不适合我
    • 您将 .htaccess 文件放在哪个目录中,您是否在父 vhost 中设置了 AllowOverride ?
    • 我不认为@avinashhiremath 正在寻找重定向。我敢肯定,这里的目的是对 PHP 文件进行内部重写。另外,您在重写模式中包含了localhost,这是无效的。
    • 我已将 .htaccess 放在项目目录中,并在 httpd-xampp.conf 中设置了 Allowoverride All
    • @Mike,我希望将localhost/project/any_string 重定向到localhost/project/test.php
    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    相关资源
    最近更新 更多