您的位置:首页 > 运维架构 > Apache

wordpress + apache 配置url rewirte

2015-11-15 13:16 459 查看

wordpress + apache 配置url rewirte

原文写于 2013-08-13 https://github.com/kuitos/kuitos.github.io/issues/2

最近在倒腾帮助中心的过程中接触到wordpress,为了方便的调试于是在内网虚拟机上搭建了一个LAMP环境,使用的是网上提供的xampp一键安装包。附上安装包地址

由于业务的需求,要在各个产品跳转到帮助中心具体的wordpress之前通过一个页面去接收请求,然后由该页面转发请求,如:

页面请求
http://help.fenxibao.com/channel/
–> 应用服务器 –> 去部署目录寻找应用名为channel的wordpress。

改为:
http://help.fenxibao.com/channel/
–>
http://help.fenxibao.com/index.php?app=channel
–> index.php做处理 –> 跳转到指定的wordpress。

自然要到apache下面去做配置,在httpd.conf中加上这些内容(xampp安装之后apache的配置文件在 /opt/lampp/etc/httpd.conf):

# 这一行配置一定要写啊,不然下面写再多的rewrite rule都是白搭啊,说多了都是泪啊。。
RewriteEngine on
<VirtualHost _default_:80>
RewriteCond %{REQUEST_URI} ^/([a-z0-9_-]+)/$
RewriteRule ^/([a-z0-9_-]+)/ /index.php?app=$1
</VirtualHost>


这里对这几行配置作一下说明:

RewriteEngine on : 功能如其名

RewriteCond string regexCode : 当string满足regexCode的正则条件时,执行后面的重写规则

RewriteRule regex1 regex2 : 定义重写规则,将regex1正则匹配到的部分采用regex2来重写

具体处理步骤:

请求url:http://help.fenxibao.com/channel/

进入RewriteCond : request uri满足条件^/([a-z0-9_-]+)/$

进入RewriteRule :重写请求url中满足条件^/([a-z0-9_-]+)/ 的部分,将其替换为/index.php?app=1,1即为正则匹配到的那部分内容,这里就是channel

OK,浏览器输入地址满心期待奇迹出现的一刻,结果chrom把wordpress打出来了。。。

查看中转页面代码:

<?php
$appName = $_GET['app'];
if ($appName == "channel"){
echo $appName;
header('Location: ../wordpress/index.php');
} else {
echo $appName;
}
?>


在这个中转界面将请求转发到 ../wordpress/index.php这个页面,应该没问题的,这个请求不符合RewriteCond的条件,应该可以直接访问应用页面的。。经过各种尝试发现在直接访问/wordpress/index.php时url被重定向成/wordpress/,这样的话就满足RewriteCond,于是请求过程变成了:

http://help.fenxibao.com/channel/
–>
locahost/index.php?app=channel
–>
lcoahost/wordpress/index.php
–>
locahost/wordpress/
–>
locahost/index.php?app=wordpress
–> echo “wordpress” 。。。

跟踪lcoahost/wordpress/index.php的源代码,实在是找不到在哪个地方做了url处理,google wordpress index.php,如获至宝:

<?php
/*
Plugin Name: Disable Canonical URL Redirection
Description: Disables the "Canonical URL Redirect" features of WordPress 2.3 and above.
Version: 1.0
Author: Mark Jaquith
Author URI: http://markjaquith.com/ */

remove_filter('template_redirect', 'redirect_canonical');
?>


将这段代码做成插件然后在wordpress里面启用,浏览器键入地址,世界顿时清静。。。

附上地址:http://wordpress.org/support/topic/how-can-i-turn-off-wordpress-indexphp-redirect-to-domain-root

最后只想引用帖子里的一句回复,Dude, you rock. That plugin script works like a charm.

后续跟进

在后续操作中发现
RewriteCond %{REQUEST_URI} ^/([a-z0-9_-]+)/$
这个东西其实是有问题,因为当我访问wordpress的具体文章时候,页面链接为
http://10.200.187.70/wordpress/?p=25
之类的链接,这个时候页面竟然又跳转到中间页面index.php,然后转发到了wordpress的首页。各种尝试无果的情况下只得用蹩脚的英文去stackoverflow上提问,stack上果然是牛人聚集地啊,给出的回复:

%{REQUEST_URI} excludes the query string (the part after the ?)`

解决方案:

RewriteCond %{QUERY_STRING} ^$
RewriteRule /([\w-]+)/?$ /test.php?app=$1 [L]


OK,it works!!

让我再欢呼一句:Dude, you rock. Your codes works like a charm.

附上问题链接:这里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  apache wordpress lamp