views:

33

answers:

1

Hi guys heres the scene - I'm building a web application which basically creates accounts for all users. Currently its setup like this the file structure:

root/index.php
root/someotherfile.php
root/images/image-sub-folder/image.jpg
root/js/somejs.js

When users create an account they choose a fixed group name and then users can join that group. Initially I thought of having an extra textbox in the login screen to enter the group the user belongs to login to. BUt I would like instead to have something like virtual folders in this case:

root/group-name/index.php

I heard it can be done with apache mod rewrite but I'm not sure how to do this - any help here?

Basically instead of having something like &group-name=yourGroupName appended to every page I would just like something of the nature above.

+2  A: 

You can configure Mod Rewrite in a .htaccess file, e.g.

root/.htaccess:

RewriteEngine On

#make sure that urls which already represent files or directories are not rewritten
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#update this if the files are not actually in /root
RewriteBase /root 

RewriteRule ^([^/]+)/(.*\.php)$ $2?group-name=$1 [L,QSA]

So any request matching /[groupname]/[php file] should be re-written to /[php file]?group-name=[groupname].

  • L means this is the last rule, so if it matches don't continue running other rules
  • QSA means append the original query string (so other GET parameters are still passed to the PHP script)

You could maybe replace the pattern which matches the groupname ([^/]+) with something more restrictive, e.g. ([a-zA-Z0-9_-]+).

You can also put the configuration in one of your apache configuration files, which can be faster than parsing the .htaccess file on every request.

Tom Haigh
Great how can I set it so that it skips certain folders like img and css etc
Ali
@Ali: that shouldn't be a problem, but i've updated my answer
Tom Haigh
Not working :( I get a 404 error. Actually my site is currently on a subdomain the url is like this: subdomain.domain.com/rootfolder/index.php... there is another htaccess file but that is not in this rootfolder and instead in the websites actual root domain folder - could that be causing issues ? I doubt it
Ali
@Ali: you might need to change the 2nd part of the RewriteRule where it says `/root/$2` to `/rootfolder/$2`. Or just change it to `$2` , and add `RewriteBase /rootfolder` on the line before.
Tom Haigh
Yep thanks for the solution works like a charm :D
Ali