代码之家  ›  专栏  ›  技术社区  ›  Elle H

Apache重写和跳过逻辑

  •  0
  • Elle H  · 技术社区  · 16 年前

    我几乎撞到了一堵墙。据我所知,这应该管用,但不行。

    我有一个本地开发地址,通配符子域为*.localhost,友好的URL为/[0-9]/somestring。我想做的是拥有 username.localhost/1/page localhost?pageId=1&username=username . 复杂的问题在于,试图让username.localhost的主页和单个页面(即username.localhost/1/page)同时工作。

    RewriteRule ^([0-9]+)/[a-zA-Z0-9\-\_\,\.]+$ - [S=1]
    RewriteCond %{HTTP_HOST} !^www.* [NC]
    RewriteCond %{HTTP_HOST} ^([^\.]+)\.localhost
    RewriteRule ^index.php$ index.php?username=%1
    RewriteRule ^([0-9]+)/[a-zA-Z0-9\-\_\,\.]+$ index.php?pageId=$1&username=%1
    

    对于/1/页的页面,第一个规则是跳过匹配项和跳过,但未能正确重写。但是,如果删除前2个规则,它将重写/1/页的页面。

    它好像没有跳过,但是如果我把它改为s=2,它就会跳过这两个规则。哎呀。有什么想法吗?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Tim Stone    15 年前

    据我所知,事实上 做你期望它做的。只有这样做之后,它才会在你的规则设置上有第二个步骤,这会把事情搞砸。发生的事情看起来更具体如下:

    • 请求到 http://username.localhost/1/page 被制成
    • 输入 1/page 符合第一条规则, S=1 应用
    • 输入 1页 与第三条规则匹配,URL重写为 index.php?pageId=1&username=username
    • 内部重定向由执行 mod_rewrite (到目前为止都很好,但是…)
    • MODY重写 处理内部重定向,并重新开始处理规则
    • 输入 index.php 与第一条规则不匹配, S=1 未应用
    • 输入 索引文件 与第二条规则匹配,URL重写为 index.php?username=username
    • (内部重定向再次发生,执行相同的重写,但是 MODY重写 检测重定向循环并立即停止处理)

    有几种不同的方法可以解决这个问题,但我认为这里最简单的方法是确保文件不存在,然后将模式从上一个规则滚动到前一个规则的条件中:

    # Make sure we haven't rewritten to a file yet (the "directory" gets processed
    # before DirectoryIndex index.php is applied)
    RewriteCond %{REQUEST_FILENAME} !-f
    # Check that the input doesn't match the pattern we want handled later
    RewriteCond $0           !^([0-9]+)/[a-zA-Z0-9_,.-]+$
    RewriteCond %{HTTP_HOST} !^www.* [NC]
    RewriteCond %{HTTP_HOST}  ^([^\.]+)\.localhost
    RewriteRule ^.*$ index.php?username=%1
    
    RewriteRule ^([0-9]+)/[a-zA-Z0-9_,.-]+$ index.php?pageId=$1&username=%1
    

    编辑 :上面的版本还捕获了与您的页面模式不匹配的内容,并表现得像 索引?用户名=用户名 可能不需要。以下内容将避免这种情况,而且更为简洁:

    RewriteCond %{HTTP_HOST} !^www.* [NC]
    RewriteCond %{HTTP_HOST}  ^([^\.]+)\.localhost
    RewriteRule ^$ index.php?username=%1
    
    RewriteRule ^([0-9]+)/[a-zA-Z0-9_,.-]+$ index.php?pageId=$1&username=%1
    
    推荐文章