Apache 地址重写简单介绍

来源:互联网 发布:桌面提醒便签软件 编辑:程序博客网 时间:2024/05/02 01:48

一、为何需要地址重写

网页地址变化,SEO需要更友好的地址,域名变化,等等情况下,为了让客户受尽了少的影响,最好的办法就是地址重写。

 

二、在那里重写

1、在Apache主配置文件httpd.conf中;以我本地XAMPP为例,就是要修改下面配置文件: D:/xampp/apache/conf/httpd.conf ;

2、在httpd.conf里定义的虚拟主机配置中;

如果你在一个Apache中配置了多个站点,就需要在VirtualHost中设置你的地址重写规则。

参看: APACHE多站点配置方法

Ubuntu中Apache多站点设置

3、在基于目录的配置文件.htaccess中;

.htaccess文件是针对目录进行配置的一种方法。Apache在提供一个资源时,会在此资源所在目录中寻找.htaccess文件,如果有,则使其中的指令生效。就类似ASP.net 中每个目录下都可以设置 Web.config 文件,下级目录的覆盖上级目录的配置;

 

三、重写是如何工作的

首先要确认已经编译加载了 mod_rewrite 模块:

在 D:/xampp/apache/conf/httpd.conf 文件中,确认下面加载模块的代码没有被注释掉:

LoadModule rewrite_module modules/mod_rewrite.so

当外部请求到达Apache,Apache会调用重写规则中的定义来重写由用户浏览器指定请求的URL,最后被重写的URL如果是重定向,则送交浏览器做再一次请求;如果是代理则把重写后的URL交给代理模块请求最终的内容(Content),最后把内容送回给浏览器。

 

四、如何重写

以基于目录的配置文件.htaccess来重写为例演示如何重写:

1、假如您对网站内容所在的服务器没有管理员权限,或者您的网站内容放在ISP的服务器上托管,无法改写主配置文件,但是您对Web站点内容所在的目录有写权限,则可以设置自己的.htaccess文件达到同样的目的。但您需要确定主配置文件中对您的网站所在的目录定义了下面的内容,否则您的.htaccess不会工作。 如下的 AllowOverride All 是必须的,否则.htaccess文件不起作用。

#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride All
Order deny,allow
Deny from all
</Directory>

<Directory "D:/xampp/htdocs">
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
</Directory>

2、 在 D:/xampp/htdocs 目录下建立一个 .htaccess 文件,

.前面没有信息的 .htaccess 文件,一般方式建立是不行的,建立方式参看这篇文章: Windows下自由创建.htaccess文件的N种方法

3、一个简单的.htaccess 文件配置演示

下面就是一个简单的 .htaccess 文件 配置,把对 http://localhost:8081/11 的请求跳转到 /my/2.php 来处理。

RewriteEngine on
RewriteBase /
RewriteRule ^11$ /my/2.php

 

有关 .htaaccess 文件的更详细的配置信息可以参看:

http://man.chinaunix.net/newsoft/Apache2.2_chinese_manual/howto/htaccess.html

 

参考资料:

Apache重写规则的常见应用及实例说明
http://9host.cn/php/200742218323311482.html

含参数url(即url中带?)的apache重写问题
http://blog.csdn.net/linglongwunv/archive/2010/01/12/5183019.aspx

Apache重写规则的常见应用
http://777yjt.blog.163.com/blog/static/950693520061136304519/

ApacheURL重写简介
http://cdwenyang.blog.163.com/blog/static/13569222007101411151535/

.htaccess文件
http://man.chinaunix.net/newsoft/Apache2.2_chinese_manual/howto/htaccess.html

Apache模块 mod_rewrite
http://lamp.linux.gov.cn/Apache/ApacheMenu/mod/mod_rewrite.html

如何利用Apache的Rewrite功能实现动态网址到静态网址的转换
http://www.coolder.com/255-1-1

原创粉丝点击