using mod_rewrite to simulate multiple sub-directo

2020-05-06 14:12发布

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 bbb rather than aaaaa/bbb.

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

5条回答
劳资没心,怎么记你
2楼-- · 2020-05-06 14:21

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-05-06 14:21

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).

查看更多
Emotional °昔
4楼-- · 2020-05-06 14:24

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.

查看更多
We Are One
5楼-- · 2020-05-06 14:29

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')

查看更多
SAY GOODBYE
6楼-- · 2020-05-06 14:38

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.

查看更多
登录 后发表回答