友好的URL工作但不重写

时间:2016-01-29 19:44:50

标签: regex apache .htaccess mod-rewrite

我有以下.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Rewrite www.site.com.br/usuarios.php?user=Igor&area=inicio to
    # www.site.com.br/Igor/inicio
    RewriteCond %{THE_REQUEST} /usuarios\.php\?user=([^&\s]+)&area=([^&\s]+) [NC] 
    RewriteRule ^ /%1/%2? [R=302,L,NE]

    # Rewrite www.site.com.br/usuarios.php?user=Igor to
    # www.site.com.br/Igor if not have the second parameter
    RewriteCond %{THE_REQUEST} /usuarios\.php\?user=([^&\s]+) [NC] 
    RewriteRule ^ /%1? [R=302,L,NE]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule ^((?!usuarios/|posts/).*)$ usuarios.php?q=$1 [L,NC]

    # Rewrite www.site.com.br/posts.php?post=HelloWorld to
    # www.site.com.br/posts/HelloWorld
    RewriteRule ^posts/(.*) posts.php?post=$1 [L,QSA]
</IfModule>

我的问题出在上一个RewriteRuleRewriteRule ^posts/(.*) posts.php?post=$1 [L,QSA]。如果我访问www.site.com.br/posts/HelloWorld,则效果很好,如果我访问www.site.com.br/posts.php?post=HelloWorld也可以,但不会重写为www.site.com.br/posts/HelloWorld

怎么做?

1 个答案:

答案 0 :(得分:1)

您还需要一个重定向规则

<IfModule mod_rewrite.c>
    Options -MultiView
    RewriteEngine On

    # Rewrite www.site.com.br/usuarios.php?user=Igor&area=inicio to
    # www.site.com.br/Igor/inicio
    RewriteCond %{THE_REQUEST} /usuarios\.php\?user=([^&\s]+)&area=([^&\s]+) [NC] 
    RewriteRule ^ /%1/%2? [R=302,L,NE]

    RewriteCond %{THE_REQUEST} /posts\.php\?post=([^&\s]+) [NC] 
    RewriteRule ^ /post/%1? [R=302,L,NE]

    # Rewrite www.site.com.br/usuarios.php?user=Igor to
    # www.site.com.br/Igor if not have the second parameter
    RewriteCond %{THE_REQUEST} /usuarios\.php\?user=([^&\s]+) [NC] 
    RewriteRule ^ /%1? [R=302,L,NE]

    # Rewrite www.site.com.br/posts.php?post=HelloWorld to
    # www.site.com.br/posts/HelloWorld
    RewriteRule ^posts/(.*) posts.php?post=$1 [L,QSA]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^((?!usuarios/|posts/).*)$ usuarios.php?q=$1 [L,NC]

</IfModule>