htaccess重写相当url而不改变rewritebase

时间:2016-08-04 20:58:40

标签: apache .htaccess mod-rewrite

试图在不更改RewriteBase的情况下重写几个不同的URL。带有查询的以下网址:

http://example.com/directory1/directory2/job?id=100
http://example.com/directory3/directory4/profile?id=200

会变成:

http://example.com/directory1/directory2/job/100
http://example.com/directory3/directory4/profile/200

目前的规则:

RewriteRule ^directory1/directory2/job/([0-9]+)$ ./directory1/directory2/job?id=$1 [L,QSA]

RewriteRule ^directory3/directory4/profile/([0-9]+)$ ./directory3/directory4/profile?id=$1 [L,QSA]

完整的htaccess:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
        Options +FollowSymLinks
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    RewriteRule ^directory1/directory2/job/([0-9]+)$ ./directory1/directory2/job?id=$1 [L,QSA]

    RewriteRule ^directory3/directory4/profile/([0-9]+)$ ./directory3/directory4/profile?id=$1 [L,QSA]

</IfModule>

1 个答案:

答案 0 :(得分:1)

按此顺序制定规则:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
        Options +FollowSymLinks
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    RewriteCond %{THE_REQUEST} (/directory1/directory2/job)\?id=([^\s&]+) [NC]
    RewriteRule ^ /%1/%2? [R=302,L,NE]

    RewriteCond %{THE_REQUEST} (/directory3/directory4/profile)\?id=([^\s&]+) [NC]
    RewriteRule ^ /%1/%2? [R=302,L,NE]

    RewriteRule ^(directory1/directory2/job)/([0-9]+)$ $1?id=$2 [L,QSA]

    RewriteRule ^(directory3/directory4/profile)/([0-9]+)$ $1?id=$2 [L,QSA]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

</IfModule>