【问题标题】:mod-rewrite when index.php is in the URL当 index.php 在 URL 中时 mod-rewrite
【发布时间】:2015-10-27 07:05:17
【问题描述】:

我希望将http://example.com/admin/pages/index.php 重写为http://example.com/index.php?admin=admin&cid=pages

它适用于http://example.com/admin/pages(我也想要),但不适用于http://example.com/admin/pages/index.php

这是如何实现的?

重写引擎开启 重写基础/

# If the request is for a valid directory, file, or link, don't do anything
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

#remove the trailing slash
RewriteRule (.+)/$ $1

# If you add this first rule to support views, be sure to remove the QSA flag from the second rule (maybe not required since the first rule has the L flag)
#replace admin/cid with index.php?admin=admin&cid=cid
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?admin=$1&cid=$2 [L,QSA]
#replace mypage with index.php?admin=mypage
RewriteRule ^([^/]+)/?$ index.php?admin=$1 [L,QSA]

编辑

随机变化表明这可能是正确的。

    RewriteRule ^([^/]+)/([^/]+)/index.php/?$ index.php?admin=$1&cid=$2 [L,QSA]
    RewriteRule ^([^/]+)/([^/]+)/?$ index.php?admin=$1&cid=$2 [L,QSA]
    #replace mypage with index.php?admin=mypage
    RewriteRule ^([^/]+)/index.php/?$ index.php?admin=$1 [L,QSA]
    RewriteRule ^([^/]+)/?$ index.php?admin=$1 [L,QSA]

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite


    【解决方案1】:

    问题是您从规则中跳过所有文件和目录的第一条规则。

    用这个替换你的规则:

    RewriteEngine On
    
    RewriteRule ^index\.php$ - [L,NC]
    
    #remove the trailing slash
    RewriteRule (.+)/$ $1 [L,R=302]
    
    # If you add this first rule to support views, be sure to remove the QSA flag from the second rule (maybe not required since the first rule has the L flag)
    #replace admin/cid with index.php?admin=admin&cid=cid
    RewriteRule ^([^/]+)/([^/]+)(?:/?|/index\.php)$ index.php?admin=$1&cid=$2 [L,QSA]
    
    #replace mypage with index.php?admin=mypage
    RewriteRule ^([^/.]+)/?$ index.php?admin=$1 [L,QSA]
    

    【讨论】:

    • 似乎不起作用。你能解释一下RewriteRule (?:^|/)index\.php$ - [L,NC]吗?谢谢
    • 感谢 anubhava,它现在似乎可以工作了。你能解释一下(?:/?|/index\.php) 在做什么吗?另外,RewriteRule ^index\.php$ - [L,NC] 说总是删除index.php,所以它可能会被写回,对吗?
    • 我之前已经删除了RewriteRule (?:^|/)index\.php$ - [L,NC]RewriteRule ^index\.php$ - [L,NC] 如果当前URI 是/index.php 基本上停止重写
    猜你喜欢
    • 1970-01-01
    • 2013-12-07
    • 2012-07-21
    • 2012-05-02
    • 1970-01-01
    • 2014-12-31
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多