使用 Apache mod_rewrite 将主机重写到子文件夹,但它会重定向而不是重写

使用 Apache mod_rewrite 将主机重写到子文件夹,但它会重定向而不是重写

我想通过 .htaccess 模拟虚拟主机,所以我想将主机名重写为子文件夹。它可以工作,但在某些 URL 上它不会重写而是重定向。

这是我的.htacess 文件:

RewriteEngine on
RewriteBase /

# Rewrite from subdomains to subfolders with builds
RewriteCond %{HTTP_HOST} ^(.*)\.(.*)\.ci\.example\.com$
RewriteCond %{REQUEST_URI} !^/builds/
RewriteCond %{REQUEST_URI} !^/robots.txt
RewriteRule ^(.*)$ /builds/%2/%1/$1 [PT]


# Example project
RewriteCond %{HTTP_HOST} ^old\.domain\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
# Rewrite production to master subfolder
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteCond %{REQUEST_URI} !^/builds/
RewriteRule ^(.*)$ builds/example-project/master/$1 [PT]

例如,如果我访问,http://example.com/它将正确重写为/builds/sum/folder。如果访问http://example.com/page.html,它将重写为/builds/sum/folder/page.html。但如果我访问,http://example.com/folder它将不会重写,而是 301 重定向到/builds/sum/folder/folder(并在那里加载index.html)。

为什么它总是重写,但如果目标路径不是现有文件而是包含 index.html 的文件夹,则会重定向?(我想重写所有内容,因此浏览器中的 URL 不会改变。)

编辑:为了更好地理解发生了什么:

Bobik-MBP:Sites Bobik$ telnet www.example.com 80
Trying 1.2.3.4...
Connected to example.com.
Escape character is '^]'.
GET http://www.example.com/folder
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://www.example.com/builds/sub/folder/">here</a>.</p>
</body></html>
Connection closed by foreign host.

$ telnet www.example.com 80
Trying 1.2.3.4...
Connected to example.com.
Escape character is '^]'.
GET http://www.example.com/folder/index.html
<!DOCTYPE html>
<html>
... (requested page)

相关内容