乐者为王

Do one thing, and do it well.

.htaccess实例详解

又一次迁移博客服务器。因为是迁移,就没有采取安装的方式,而是把以前的程序拷贝到新服务器上。

打开首页的时候没问题,访问具体文章时就出错了:

1
2
Not Found
The requested URL /sample-article.html was not found on this server.

试着去后台重新做设置,然后就发现在根目录下多了个.htaccess文件,内容如下:

1
2
3
4
5
6
7
8
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

以前也看过这个文件,总是模模糊糊不太明白。今天研究的时候发现一下子就清清楚楚了(这大概就是佛家所说的顿悟吧,不过它的发生应该还是建立在渐修的基础上)。

下面来说说这些内容的理解:

第1行就是打开重写引擎。

第2行是设置URI前缀。

1
2
3
4
5
6
7
8
9
10
Syntax: RewriteRule Pattern Substitution [flags]

- (dash)
 A dash indicates that no substitution should be performed (the existing path
 is passed through untouched). This is used when a flag (see below) needs to
 be applied without changing the path.

last|L
 Stop the rewriting process immediately and don't apply any more rules.
 Especially note caveats for per-directory and .htaccess context.

第3行是完全匹配index.php的URI,但不做替换,并且匹配成功后就停止执行重写过程。

第6行就是把所有的访问请求重写,指给index.php,然后停止执行重写过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Syntax: RewriteCond TestString CondPattern

REQUEST_FILENAME
 The full local filesystem path to the file or script matching the request,
 if this has already been determined by the server at the time REQUEST_FILENAME
 is referenced. Otherwise, such as when used in virtual host context, the same
 value as REQUEST_URI.

You can prefix the pattern string with a '!' character (exclamation mark) to
specify a non-matching pattern.

'-d' (is directory)
 Treats the TestString as a pathname and tests whether or not it exists, and
 is a directory.

'-f' (is regular file)
 Treats the TestString as a pathname and tests whether or not it exists, and
 is a regular file.

第4和第5行是不去测试访问URI是否是目录或文件。其实有了第6行这两行基本就是摆设了。

最后再唠叨一句,有问题直接查官方文档应该是最好的选择。官方文档链接:Apache Module mod_rewrite

Comments