我正在尝试在URL中重写破折号,以便它们不在内部存在。例如此网址
本地主机/ mysite的/ 关于-我
“about-me”应改写为“aboutme”。我需要这个,因为控制器类名依赖于这个路由字符串,我显然不能使用破折号。
这是我发现的条件和规则,我认为应该符合我的需要:
# Condition is to avoid rewrite on files within specified subdirs
RewriteCond $1 !^(css|img|ckeditor|scripts)
RewriteRule ^([^-]+)-([^-]+)$ $1$2 [L]
然而,它似乎不起作用,因为控制器类 Aboutme 没有实例化。我得到了一个 404错误,而且我的名字中没有破折号的类似控制器类没有任何问题。
你能帮我个忙吗?
答案 0 :(得分:4)
为什么不选择路线?
$route['about-me'] = 'aboutme/index';
答案 1 :(得分:1)
尝试删除^和$
# Condition is to avoid rewrite on files within specified subdirs
RewriteCond $1 !^(css|img|ckeditor|scripts)
RewriteRule ([^-]+)-([^-]+) $1$2 [L]
答案 2 :(得分:1)
您可以扩展Router类 在 / application / core 中创建一个名为 MY_Router.php 的文件( MY 是默认前缀)并将其复制到其中;
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Router extends CI_Router {
function set_class($class) {
$this->class = str_replace('-', '_', $class);
}
function set_method($method) {
$this->method = str_replace('-', '_', $method);
}
function _validate_request($segments) {
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.str_replace('-', '_', $segments[0]).'.php')) {
return $segments;
}
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0])) {
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0) {
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().str_replace('-', '_', $segments[0]).'.php')) {
show_404($this->fetch_directory().$segments[0]);
}
} else {
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php')) {
$this->directory = '';
return array();
}
}
return $segments;
}
// Can't find the requested controller...
show_404($segments[0]);
}
}
这会自动重写 - 给你_
如果您不希望下划线更改代码,则无需替换它们;
str_replace('-', '_',
到str_replace('-', '',
答案 3 :(得分:1)
以下是使用mod-rewrite执行此操作的方法:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/(.*)([\w]*)-([\w]*)(.*)/?$ [NC]
RewriteRule .* %1%2%3%4 [L,DPI]
不会重定向,但可以像这样添加R=301
[R = 301,DPI,L]。
不一定是about-me
。可以在任何位置对任何单词配对。即。
localhost/mysite/about-me
= .../aboutme
或
localhost/mysite/folder1/folder2/folder3/my-folder
= .../myfolder
或
localhost/mysite/folder1/folder2/my-folder/folder3
= .../myfolder/...