Using apache mod_rewrite to parse SEO urls

How do I convert something like

me.com/profile/24443/quincy-jones

to

me.com/profile.php?id=24443

or something like

me.com/store/24111/robert-adams

to

me.com/store.php?id=24111

with mod_rewrite?

Can I do the inverse transform also with mod_rewrite, or will I have to parse it through PHP?

+3
source share
2 answers

This should work for both:

RewriteEngine on
RewriteRule ^([^/]+)/([^/]+).*$ $1.php?id=$2 [L]

Explanation:

^           - beginning of the string
([^/])      - first group that doesn't contain /
              will match both 'profile' and 'store'
              will also be referenced by $1 later
/           - first slash separator
([^/])      - second group, id in your case
              will be referenced by $2
.*          - any ending of the request uri
$           - end of request string

You can also clarify that only two requests are rewritten, and only numbers are accepted as id:

RewriteRule ^((profile|store))/(\d+).*$ $1.php?id=$2 [L]
+9
source

Make sure the apache mod_rewrite module is enabled, then:

RewriteEngine on

RewriteRule ^/profile/([^/]*)/([^/]*)$  /profile.php?id=$1 [L]

RewriteRule ^/store/([^/]*)/([^/]*)$    /store.php?id=$1 [L]

, , PHP, ( URL-). mod_rewrite , , ( ). , [L] (), ( , ).

, , URL-, .

+2

Source: https://habr.com/ru/post/1710158/


All Articles