Tutorial :mod_rewrite



Question:

My current code is something like this

store.php?storeid=12&page=3  

and I'm looking to translate it to something like this

mysite.com/roberts-clothing-store/store/12/3  

and something like this:

profile.php?userid=19  

to

mysite.com/robert-ashcroft/user/19  

I understand that it's best to have the SEO-friendly text as far left as possible, ie not

mysite.com/user/19/robert-ashcroft  

(what stackoverflow does)

I can't figure out how to do this in apache's mod_rewrite. Any help?


Solution:1

Actually, you may have to think "upside-down" with mod_rewrite.

The easiest way is that to make your PHP emit the rewritten mysite.com/roberts-clothing-store/store/12/3 links.

mod_rewrite will then proxy the request to one PHP page for rewrite.php?path=roberts-clothing-store/store/12/3 that will decode the URL and sets the arguments (here storeid and page) and dynamically include the correct PHP file, or just emit 301 for renamed pages.

A pure solution with mod_rewrite is possible, but this one is much easier to get right, especially when you don't master mod_rewrite.

The main prob could be with the overhead that might be significant but is the price of simplicity & flexibility. mod_rewrite is much faster

Update :

The other posts do answer the questionn, but they don't solve the typical duplicate-content problem that avoided by having canonical urls (and using 301/404 for all those URLs that seems ok, but aren't).


Solution:2

Try these rules:

RewriteRule ^[^/]+/store/([0-9]+)/([0-9]+)$ store.php?storeid=$1&page=$2   RewriteRule ^[^/]+/user/([0-9]+)/ profile.php?userid=$1  

But I wouldn’t use such URLs. They don’t make sense when you think of the URL path as a hierarchy and the path segments as their levels.


Solution:3

Then you can just use RewriteRule directive in a .htacces like:

RewriteRule roberts-clothing-store/store/(\d+)/(\d+)$ store.php?storeid=$1&page=$2 [L]  

See http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html for help, or google.


Solution:4

RewriteRule ^roberts-clothing-store/store/([^.]+)/([^.]+)$ store.php?id=$1&page=$2  RewriteRule ^robert-ashcroft/user/([^.]+)$ profile.php?userid=$1  


Solution:5

My approach is to make the .htaccess as easy as possible and to do all the hard work in PHP:

RewriteRule ^(.*?)$ index.php?$1  

This basically means to take everything and reroute it to my index.php file (in css/javascript/image directories I simply use "RewriteEngine off" to grand access to these files). In PHP I than just split("/", $param, 5) the string and run a foreach() to check all the parameters. Encapsulated in a nice function this works fine for me.

Update:

For this easy case I highly recommend the use of explode() instead of using split(), because explode() doesn't come with the overhead by using regular expressions.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »