网址重新规则

时间:2016-12-30 17:59:12

标签: apache .htaccess url mod-rewrite url-rewriting

这个网址如何:

www.domain.com/services.php?hello-world-be-active

可以改写为:

www.domain.com/services/hello-world-be-active

更新:

以下规则不起作用......我正在使用此规则

RewriteCond %{THE_REQUEST} ^GET\ /(.+)\.php [NC]
RewriteRule ^ /%1 [QSA,R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ /$1.php

以上规则给出以下结果:

www.domain.com/whatever.php => www.domain.com/whatever (Correct)
www.domain.com/whatever.php?whatever-whatever => www.domain.com/whatever?whatever-whatever (Not Correct because question mark '?' should replace with slash '/')

1 个答案:

答案 0 :(得分:0)

试试这个:

Options +FollowSymLinks

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /

    # Match the host, if you want
    RewriteCond %{HTTP_HOST} ^www\.domain\.com$

    RewriteCond %{REQUEST_URL} !\.php$
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^[^/]*/(.*)$ %{REQUEST_FILENAME}.php?$1 [QSA,L]
</IfModule>
## Results:
# services/whatever-here         => services.php?whatever-here
# services/whatever-here?foo=bar => services.php?whatever-here&foo=bar
# anything/whatever              => anything.php?whatever
# services/foo/bar               => services.php?foo/bar

根据这些规则,对services/whatever的任何调用都将映射到services.php文件。如果您在重写规则的末尾添加R flag,则该请求将在外部重定向改为services.php

但如果你想要反过来的话;意思是将services.php?whatever重定向到services/whatever,这就是您需要的内容:

Options +FollowSymLinks

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /

    # Match the host, if you want
    RewriteCond %{HTTP_HOST} ^www\.domain\.com$

    RewriteRule (.+)\.php $1/%{QUERY_STRING} [R,QSD,L]
</IfModule>
## Results:
# foo/bar/baz.php?qux   => foo/bar/baz/qux
# services.php?whatever => services/whatever