URL rewriting in PHP without htaccess

瘦欲@ 提交于 2019-11-26 07:38:51

问题


Website is running on a web host where we don\'t have access to a .htaccess file. However, I want to do URL rewriting for user friendly URLs.

e.g. Original URL

www.example.com/file?q=name

expected URL

www.example.com/file/name

回答1:


As other people said, just use links like /index.php/nice/looking/url.
The "index.php" in the middle of the URL might look a little strange, but I don't think it's possible to have it look better without .htaccess

Else, you could ask your hoster to redirect any URL to /index.php so that you can handle URL rewriting without having /index.php in your URL.

Then you can just use a regex match to detect what file to include.
preg_match('@[/]{1}([a-zA-Z0-9]+)@', $_SERVER["PATH_INFO"], $matches) ($matches will contain all "parts" of the url in an array)

Be careful with including the files, use a whitelist so you're sure nobody would be able to load internal files.




回答2:


as Alix Axel suggested you can use

www.example.com/index.php/file/name

then you will use $_SERVER['REQUEST_URI'] to process the URL.




回答3:


Your best bet will be to have URLs such as this:

www.example.com/index.php/file/name

You'll to rewrite your PHP code though.




回答4:


If you have an Apache server and AcceptPathInfo is enabled, then you can use the URL you wrote. A request of /file/name will then be automatically rewritten to /file with the PATH_INFO value of /name if /file is a regular file.




回答5:


Try this

www.example.com/file?q=name

to

www.example.com/name (better than www.example.com/file/name)

Open your .htaccess from your project root folder and add this code

Options +FollowSymLinks

RewriteEngine On
RewriteRule \.(js|css|jpe?g|png|gif)$ - [L]


RewriteRule "^([ \w-]+)/?$" /file?q=$1 [L,QSA]

This solves your problem. See the post how to rewrite URL in .htaccess



来源:https://stackoverflow.com/questions/2126762/url-rewriting-in-php-without-htaccess

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