Rob*_*oer 1 php apache mod-rewrite url-rewriting
感谢您的耐心和帮助.我完全重申了这个问题,因为我的所有版本都要花很长时间.我有一个PHP MVC框架,有4个入口点:
从根目录:
index.php
index-ajax.php
admin/index.php
admin/index-ajax.php
我需要一个.htcaccess文件来接受任何请求,并根据url将其重写到相应的文件中.长网址是index.php?rt = cms/view/15,我希望它是index/cms/view/15.除了一个问题之外,那部分已经完成了.
这是我的.htaccess文件:
# htaccess file for framework - GOOD
Options +FollowSymLinks
# Turn on the mod_rewrite engine - GOOD
RewriteEngine On
# Hide indexes - GOOD
Options -Indexes
# If a file is not one of these, continue processing. - GOOD
RewriteRule \.(css|js|jpg|jpeg|png|gif|ico)$ - [L]
# RewriteRules for folder index files
#RewriteRule ^(index)?(.php)?$ index.php [L] - GOOD
#RewriteRule ^admin(/?)(index)?(.php)?$ admin/index.php [L] - GOOD
# RewriteRules for admin folder arguements - going from more specific to less
RewriteRule ^admin/ajax/[A-Za-z0-9-_/]*$ admin/index-ajax.php?rt=$1 [L]
RewriteRule ^admin/[A-Za-z0-9-_/]*$ admin/index.php?rt=$1 [L]
# RewriteRule for root ajax file
RewriteRule ^ajax/[A-Za-z0-9-_/]*$ index-ajax.php?rt=$1 [L]
# RewriteRule for root file - by here, it is not ajax or admin related, so only
# possible option left if the root index file
RewriteRule ^[A-Za-z0-9-_/]*$ index.php?rt=$1 [L]
Run Code Online (Sandbox Code Playgroud)
我创建了一个带有两个文件夹的简单站点 - "root"和"root/admin",并且每个文件夹中包含一些带有虚拟内容的css,images和javascript文件夹.在'root'和'root/admin'中有一个index.php和index-ajax.php文件,无论url参数是什么,它都会输出简单的输出,并使用每个文件夹中的css,js和image文件.
我现在的问题是,如果我做一个像index/blah或/ admin/index/blah这样的URL,那么页面显示正确,参数是正确的.然而,当我做一个像index/blah/view或admin/index/blah/view这样的url时,争论是正确的(?rt = blah/view)但是页面出错了,因为css/js/images文件转到索引/ blah/[css]而不是index/[css].
关于如何处理这个问题的任何想法?我允许css/js/image文件通过.htaccess进行处理,因此那里的工作量会减少.
你确定一切都应该由index.php处理吗?那些静态文件如images/css等呢?
这是您可能感兴趣的替代方法.您可以将任何尚未作为文件或目录存在的URL转发到index.php文件,然后在那里解析URL,例如[domain.com]/cms/view/15将被重写为[domain.com]/index.php/cms/view/15.对于此工作,您需要将apache指令AcceptPathInfo设置为On.
的.htaccess:
RewriteEngine On
#check url is not a valid file
RewriteCond %{REQUEST_FILENAME} !-f
#check url is not a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
#rewite anything left
RewriteRule ^(.*)$ index.php/$1 [L]
Run Code Online (Sandbox Code Playgroud)
的index.php
$path = trim($_SERVER['PATH_INFO'], '/');
$pathParts = explode('/', $path);
if (isset($pathParts[0])) {
$com = $pathParts[0];
} else {
$com = 'defaultcom';
}
//$com[1] will be 'view' if supplied
//$com[2] will be 15 if supplied
Run Code Online (Sandbox Code Playgroud)
我喜欢这种方法,因为您不必在apache配置中定义和理解URL,但您可以在PHP中完成大部分工作.
编辑
你可以使用它作为你的.htaccess,这会将任何带有不在列表中的扩展名的请求重定向到你的PHP脚本.RewriteCond应该停止对admin文件夹的请求被重写.
RewriteEngine On
#don't rewrite admin
RewriteCond %{REQUEST_URI} ^admin/
#rewrite anything with a file extension not in the list
RewriteRule !\.(js|gif|jpg|png|css|ico)$ /index.php [L]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2477 次 |
| 最近记录: |