using mod_rewrite to simulate multiple sub-directories

…衆ロ難τιáo~ 提交于 2019-12-02 17:59:47

问题


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?


回答1:


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




回答2:


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




回答3:


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.




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/5282566/using-mod-rewrite-to-simulate-multiple-sub-directories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!