Klav Klav - 3 months ago 11
Apache Configuration Question

htaccess rewrite pretty url without changing rewritebase

Attempting to rewrite a few different URLs without changing the RewriteBase. The following URLs with queries:

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


would become:

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


Currently rules:

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]


Full 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>

Answer

Have your rules in this order:

<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>
Comments