【问题标题】:mod_rewrite and php variablesmod_rewrite 和 php 变量
【发布时间】:2011-04-04 17:28:10
【问题描述】:

我正在尝试让 mod_rewrite 与我的网站一起使用,但由于某种原因它无法正常工作。 我已经在我的 .htaccess 文件中输入了代码来将非 www 重定向到 www,所以我知道 mod_rewrite 正常工作。

我要更改的网址是example.com/index.php?p=home,所以新网址是example.com/page/home

但是,当我尝试此代码时,我只是得到一个 404,告诉我 /page/home 不存在。

Options +FollowSymLinks

RewriteEngine on

RewriteRule index/p/(.*)/ index.php?p=$1
RewriteRule index/p/(.*) index.php?p=$1

谁能帮帮我?

【问题讨论】:

    标签: .htaccess mod-rewrite


    【解决方案1】:

    您的重写规则使用 index/p/xxxxx 但您想要 /page/xxxx

    试试

    RewriteRule ^/page/(.*)/ index.php?p=$1
    RewriteRule ^/page/(.*) index.php?p=$1
    

    【讨论】:

    • 这是我应该在我的原始帖子中放入的内容。很抱歉造成混乱。
    【解决方案2】:

    您的模式与您的示例网址不匹配。假设您的示例 URL 是正确的,您需要的是:

    Options +FollowSymLinks
    
    RewriteEngine on
    
    # We want to rewrite requests to "/page/name" (with an optional trailing slash)
    # to "index.php?p=name"
    #
    # The input to the RewriteRule does not have a leading slash, so the beginning
    # of the input must start with "page/". We check that with "^page/", which
    # anchors the test for "page/" at the beginning of the string.
    #
    # After "page/", we need to capture "name", which will be stored in the
    # backreference $1. "name" could be anything, but we know it won't have a
    # forward slash in it, so check for any character other than a forward slash
    # with the negated character class "[^/]", and make sure that there is at least
    # one such character with "+". Capture that as a backreference with the
    # parenthesis.
    #
    # Finally, there may or may not be a trailing slash at the end of the input, so
    # check if there are zero or one slashes with "/?", and make sure that's the end
    # of the pattern with the anchor "$"
    #
    # Rewrite the input to index.php?p=$1, where $1 gets replaced with the
    # backreference from the input test pattern
    RewriteRule ^page/([^/]+)/?$ index.php?p=$1
    

    【讨论】:

    • 这非常有效。我认为 ([^/]+)/?$ 修复了它。您能否解释一下该表达式的各个部分,以便我更好地理解它?
    • @kaotix - 我现在将 cmets 添加到规则中。我不确定您对正则表达式的熟悉程度,因此我尝试尽可能详细地解释。
    猜你喜欢
    • 2010-12-02
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2012-07-16
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多