开发者

using mod_rewrite to simulate multiple sub-directories

My .htaccess file currently looks like this:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule /?([A-Za-z0-9-]+)/?$ index.php?page=$1 [QSA,L]

It works fine for urls like http://site.com/aaaaa but for urls like http://site.com/aaaa/bbb the $_GET['page'] variable will only contain bb开发者_开发百科b rather than aaaaa/bbb.

Is there a way to get all of the sub-directories in the page variable?


I suggest adding / to the list of accepted characters in your last line: /?([A-Za-z0-9/-]+)/?$.


Why not just capture everything ?

Like this, I suppose :

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) temp.php?page=$1 [QSA,L]


With this (considering my script is in the temp folder), both http://tests/temp/blah and http://tests/temp/blah/glop get redirected to temp.php, with $_GET['page'] containg 'blah' or 'blah/glop'.


That's generally what's done with Zend Framework, for instance (see here for a reference).


On this line:

RewriteRule /?([A-Za-z0-9-]+)/?$ index.php?page=$1 [QSA,L]

You missed out the ^ to match the entire string. Also, in your string you want to match / in the URL. So it should have been:

RewriteRule ^/?([A-Za-z0-9-/]+)/?$ index.php?page=$1 [QSA,L]

Missing out ^ will get you the last ungreedy match.


Is there any reason you are using those ranges of characters?

Why not use:

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

Also the danger is using something like this is you could miss the "page" GET variable. I'm not sure which gets precedence, but either is bad behaviour.

Examples I've seen of this behaviour don't pass the path through as a GET parameter, but instead use php to extract it from $_SERVER['REQUEST_URI')


If you only want to allow the characters [A-Za-z0-9-] in each path segments, try this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([A-Za-z0-9-]+(/[A-Za-z0-9-]+)*)/?$ index.php?page=$1 [QSA,L]

By the way: You should choose one spelling, with or without trailing slash, and redirect if it’s the other form.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜