Apache Alias和多个版本的代码库

时间:2013-10-04 12:57:29

标签: php apache api codeigniter mod-rewrite

我正在尝试从Apache doc root之外的不同目录运行版本化的API。

我目前的做法是使用Alias directive

来尝试
Alias /api/v1.2/ /var/www/api-v1.2/
Alias /api/v1.1/ /var/www/api-v1.1/

这工作正常,但是我使用的是一个PHP框架(Codeigniter),它使用mod_rewrite将所有请求路由到我的index.php前端控制器:

RewriteCond %{REQUEST_URI} !=/server-status
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/?$1 [L]

我可以通过URL访问实际文件,alias指令工作正常。当我访问系统意味着重写的URL时,请求从doc root提供。

如何让我的CI应用程序遵循Alias规则,同时仍将流量路由到每个相应的前端控制器?

编辑:要清楚,我有3个独立版本的CI代码库:Apache doc root中有1个,每个别名目录中有2个。我想根据URL将请求路由到正确版本的代码库(如果没有匹配别名,则默认为doc根目录。)

/var/www/html (doc root)
/var/www/api-v1.2
/var/www/api-v1.1

2 个答案:

答案 0 :(得分:0)

所以,问题在于你没有阻止你的初始.htaccess重写文件夹。

您将需要3个.htaccess个文件,一个位于根目录中,另一个位于v1.1和v1.2文件夹中。

Root(docroot):

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} !=/server-status
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|robots\.txt|api/v1.1|api/v1.2)
RewriteRule ^(.*)$ index.php/$1 [L]

重要的一行是最后RewriteCond,它告诉apache忽略api文件夹。

api-v1.1文件夹:

RewriteEngine on
RewriteBase /api/v1.1
RewriteCond %{REQUEST_URI} !=/server-status
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

api-v1.2文件夹:

RewriteEngine on
RewriteBase /api/v1.2
RewriteCond %{REQUEST_URI} !=/server-status
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

重要的一行是RewriteBase。这告诉apache我们正在处理的目录,并将根据其名称处理重写。

答案 1 :(得分:0)

所以,我认为这非常简单。您希望确保一组重写条件(RewriteCond)在一种情况下不匹配 - 当它们以" / api"开头时或" api" - 所以他们不会触发重写规则。

因此,只需将此行添加到CodeIgniter重写条件的顶部:

RewriteCond %{REQUEST_URI} !(^(/)?api)

当您的请求URI(" http://example.com/")之后的部分以/ api或api开头时,这将阻止匹配这组条件。任何不匹配/ api或api的请求URI都将触发CodeIgniter规则。

mod_rewrite有两个秘密:
1)它打破了传入请求成标记:所述HTTP_HOST(例如" http://example.com&#34),所述REQUEST_URI({的{3}}之后的部分 - 像说,的index.php )和可选的QUERY_STRING(在&#34之后的部分; http // example.com / index.php?test = 3")。

2)然后你可以使用perl正则表达式匹配这些标记,并重写url指向一个资源,或者真的,做任意数量的URL重写或替换。

参考文献:
1)重写教程:http://example.com
2)重写参考:http://httpd.apache.org/docs/2.2/rewrite/intro.html
3)正则表达式备忘单:http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html