Routing URLs in PHP

落花浮王杯 提交于 2019-11-27 15:10:56

Use mod_rewrite to route everything to a single index.php file. Then check the variable in $_SERVER['REQUEST_URI'] within this file to dispatch to the required handler.

This configuration will enable mod_rewrite, if it's installed:

DirectorySlash Off
Options FollowSymLinks Indexes
DirectoryIndex index.php

RewriteEngine on

RewriteCond %{REQUEST_FILENAME}  -d
RewriteRule  ^.*$  -  [L]

RewriteCond %{REQUEST_FILENAME}  -f
RewriteRule  ^.*$  -  [L]

RewriteRule ^.*$    index.php [L]
Martin Thoma

Like trolskn (+1) describes:

Use mod_rewrite to route everything to a single index.php file. Then check the variable in $_SERVER['REQUEST_URI'] within this file to dispatch to the required handler.

But I found the following .htaccess (placed in the folder with the index.php which should "consume" everything after it) much more helpful:

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Also I would like to note that you might encounter the message

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled
or defined by a module not included in the server configuration

This can easily be solved with sudo a2enmod rewrite && sudo service apache2 restart (source)

You might want to use PEAR's Net_URL_Mapper.

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