.htaccess不会相对于根目录重写

时间:2014-02-02 10:30:47

标签: .htaccess mod-rewrite

我尝试创建一个.htaccess文件来执行以下操作:

www.domain.com/namewww.domain.com/name/定向到www.domain.com/page.php?id=name

www.domain.com/name/2www.domain.com/name/2/www.domain.com/page.php?id=name&pg=2

我的.htaccess看起来像这样:

<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteBase /

    # If the request is not for a valid directory
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    # If the request is not for a valid link
    RewriteCond %{REQUEST_FILENAME} !-l

    RewriteRule ^([a-z0-9-_\.]+)/?$ page.php?id=$1 [L]
    RewriteRule ^([a-z0-9-_\.]+)/([a-z0-9]+)/?$ page.php?id=$1&pg=$2 [L]

</IfModule>

问题是,当我在name之后实际使用斜杠时,它会将其视为目录并在www.domain.com/name/中查找页面..但我仍然可以$_GET变量基于idpg

谁能告诉我我做错了什么?我更喜欢地址栏中的网址保持干净为www.domain.com/name/2/

我还有另一个问题..我试图在没有运气的情况下重写其他网址。

如果他们写道:www.domain.com/page.php?id=name&pg=2并且想要将地址栏URL更改为再次清理,但这对我来说完全出错了。有没有具体的方法通过使用我已经做过的事情来做到这一点?

提前感谢您的帮助。

修改

解决方案基于PHP而不是.htaccess。根据这个问题找到答案:Stylesheet does not load after using RewriteRule and include。我的问题是由PHP引起的,包括相对于公共URL和目录。我被迫在任何外国包含之前定义一个主URL变量。

1 个答案:

答案 0 :(得分:2)

RewriteCond仅适用于下一个RewriteRule

以这种方式使用您的代码:

RewriteEngine On
RewriteBase /

# If the request is for a valid directory
RewriteCond %{REQUEST_FILENAME} -d [OR]
# If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} -f [OR]
# If the request is for a valid link
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+page\.php\?id=([^\s&]+) [NC]
RewriteRule ^ %1? [R=302,L]

RewriteRule ^([\w.-]+)/?$ page.php?id=$1 [L,QSA]

RewriteRule ^([\w.-]+)/([\w.-]+)/?$ page.php?id=$1&pg=$2 [L,QSA]
相关问题