开发者

How do I set up mod rewrite to do this?

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 u开发者_如何学Goser 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜