.htaccess mod rewrite automatically using php or something?

六眼飞鱼酱① 提交于 2019-12-13 06:52:52

问题


I've got a number of users, each with the website page like http://www.mysite.com/folder/artist_id.php?id=33

The users need to be able to set their own easy URL such as http://www.mysite.com/userguy that would redirect to the above page.

I know how to write these out manually in .htaccess with RewriteRule but, for example, users have a whole control panel created with php and javascript and it's become necessary to allow them to choose the name themselves and have code automatically put in. But I don't have a clue if there's already an easy method of setting that up or adding to the .htaccess file via code or if I should just do some sort of file open, rewrite thing, or what's safe.

BTW, I'm not worried about issues such as them naming themselves the same as an existing folder or php file in my site. The users are limited and subject to approval so that shouldn't be a problem.


回答1:


A proper solution that doesn't involve opening, modifying, and saving the .htaccess file using PHP would use a "router" of sorts. Consider the following:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

What this does is rewrite something like /userguy to /index.php?q=userguy, but only if /userguy isn't a directory or file that exists in the file system. This happens transparently to the user. index.php would then be responsible for do something like:

$path = $_GET['q'];
// Get router information using the $path variable.
$callback = get_callback_by_path($path);
// Assuming $callback is a function name. The function would print
// the page HTML or call into a theme layer or do whatever it needs to do.
call_user_func($callback);

The function get_callback_by_path would be custom logic that does whatever it needs to do to figure out what "userguy" needs to do. e.g. query a database mapping paths to function names and return the name of the function.

There is of course more to it, but that's the idea.




回答2:


Or, redesign your database to handle natural keys instead of numeric ones.
That'll save all your url de-mapping 33 = userguy etc, your urls will be more friendly, guessable and seo-friendly and browsing your database will be easier to boot.

username (PK)



回答3:


You could set up one rewrite rule to send all requests like http://www.mysite.com/userguy to a single php script that then will do the "translation". Doesn't necessarily have to be done via a rewrite rule, could also be an ErrorDocument handler. In this case the original request path can be found in $_SERVER['REQUEST_URI'].




回答4:


Use the RewriteMap directive to call a script that transforms the URL appropriately.



来源:https://stackoverflow.com/questions/1980721/htaccess-mod-rewrite-automatically-using-php-or-something

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