weixin

理解apache配置里的RewriteBase指令

日期: September 27, 2019 作者:网站维护

apache的文档
rewrite功能的文档

apache的文档我看得很困难,每个单词都认识,但是不知道是什么意思。

有如下几个指令

RewriteBase RewriteCond RewriteEngine RewriteMap RewriteOptions RewriteRule

RewriteBase

来看下RewriteBase这个指令的文档解释。

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

简单翻译:

这个指令指明了每个目录(或者htaccess)里RewriteRule指令的URL的前缀,RewriteRule指令是用来替换一个相对路径的。

每个目录(或者htaccess)的意思是<directory "c://xxx"></directory>或者 htaccess文件所在的目录。

再重新看下RewriteRule:

rewrite的语法: RewriteRule Pattern Substitution [flags]

第一个参数是匹配模式,第二是替换成的内容,文档里匹配模式匹配的对象是什么呢?

In per-directory context (Directory and .htaccess), the Pattern is matched against only a partial path, for example a request of "/app1/index.html" may result in comparison against "app1/index.html" or "index.html" depending on where the RewriteRule is defined.

The directory path where the rule is defined is stripped from the currently mapped filesystem path before comparison (up to and including a trailing slash). The net result (最终结果)of this per-directory prefix stripping is that rules in this context only match against the portion of the currently mapped filesystem path "below" where the rule is defined.

Directives such as DocumentRoot and Alias, or even the result of previous RewriteRule substitutions, determine the currently mapped filesystem path.

完全是考验阅读理解能力,简单地说匹配的对象就是,规则定义的路径之下的路径,比如规则定义在/foo/目录,
访问的地址是/foo/bar,那么匹配的对象就是/foo/之后的bar。

好像和rewriteBase关系不大,回到rewriteBase:

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

指定的就是rewriteRule替换的前缀,如果rewriteRule定义在/foo/路径,
访问到/foo/bar/的文件,就是匹配/foo/之后的bar/ 里的 bar/用来替换,
替换后rewriteBase就加在bar/的前面。

举个例子:

<Directory "${SRVROOT}/htdocs">
    Require all granted
    RewriteEngine On
    RewriteBase "/xxx/"
    RewriteRule "^index\.html$"  "welcome.html"
</Directory>

访问http://localhost/index.html,对应的文件路径就是${SRVROOT}/htdocs/index.html
规则定义在${SRVROOT}/htdocs/,匹配的就是之后的index.html,index替换成welcome.html
重写的路径就是 ${SRVROOT}/htdocs/xxx/welcome.html

文档里的例子:

DocumentRoot "/var/www/example.com"
AliasMatch "^/myapp" "/opt/myapp-1.2.3"
<Directory "/opt/myapp-1.2.3">
    RewriteEngine On
    RewriteBase "/myapp/"
    RewriteRule "^index\.html$"  "welcome.html"
</Directory>

Directory是一个部分(section),在指定的目录下生效(文件系统的目录)。

比如访问http://localhost/myapp

alias类似软链接,实际访问的文件路径在/opt/myapp-1.2.3,RewriteRule 把访问index.html请求,重写到welcome.html来。

比较奇怪的是,如果不设置RewriteBase,就会重写到{DocumentRoot}/opt/myapp-1.2.3/welcome.html。所以要设置一下RewriteBase,就重写到了/myapp/welcome.html来。

文档里写,这个命令在新版本的apache可能不用写。omit 理解成不做,不能理解成被忽略到不执行。但是我用的新版的还是要写。

In Apache HTTP Server 2.4.16 and later, this directive may be omitted when the request is mapped via Alias or mod_userdir.

广告内容为平台自动生成