如何使用.htaccess而不是VHost将文档根目录设置为子目录

时间:2013-05-12 22:57:30

标签: php apache .htaccess vhosts

在我的本地机器上,以下工作非常完美:

 <VirtualHost *:80>
       ##ServerAdmin postmaster@dummy-host2.localhost
       DocumentRoot "C:/xampp/htdocs/website_1"
       ServerName testpage.com/website_1
       ##ServerAlias www.recruitement.localhost
       ##ErrorLog "logs/dummy-host2.localhost-error.log"
       ##CustomLog "logs/dummy-host2.localhost-access.log" combined
 </VirtualHost>

Howerver Im将我的网站托管到名为 justhost.com 的托管公司,他们不允许我修改 httpd-vhosts.conf httpd.conf < / strong>即可。现在我的整个网站都经过编码,以便website_1下的文件引用website_1下的其他文件,使用简单的斜杠“/”表示website_1被视为文档根目录。这在本地计算机上完美运行但是当上传到主机时它会给我服务器错误,因为它无法找到文件,因为它试图在 public_html

中找到这些文件

例如:

  public_html
      - website_1
         - script.php
         - style.css

在我的 script.php 中:

<a href="/style.css">See My Style</a>

这在本地计算机上运行良好但在主机上失败,因为它试图在 public_html 下找到style.css而不是 public_html / website_1

有没有办法在不使用VHost的情况下拥有多个文档根?喜欢使用.htaccess或其他东西。我想尽量避免重写代码,因为它大约有10万行代码。

3 个答案:

答案 0 :(得分:10)

通过httpd.conf启用mod_rewrite和.htaccess,然后将此代码放在.htaccess目录下的DOCUMENT_ROOT中:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{DOCUMENT_ROOT}/website_1/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/website_1/$1 -d [OR]
RewriteCond %{DOCUMENT_ROOT}/website_1/$1 -l
RewriteRule (?!^website_1/)^(.*)$ /website_1/$1 [R=302,L,NC]

验证一切正常后,将R=302替换为R=301。在测试mod_rewrite规则时,请避免使用R=301(永久重定向)。

答案 1 :(得分:3)

在.htaccess中输入一个条目。假设您有一个网站abc.com。您想在目录中运行另一个网站。然后在父目录中创建指向abc.com的.htaccess

RewriteEngine on

RewriteCond %{HTTP_HOST} ^abc.com$ [NC,OR]

RewriteCond %{HTTP_HOST} ^www.abc.com$ 

RewriteCond %{REQUEST_URI} !subdirectory/

RewriteRule (.*) /subdirectory/$1 [L]

答案 2 :(得分:2)

将所有图像请求重写为root可能是一种解决方案。您可以在根目录下的一个.htaccess文件中尝试此操作:

Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /

# Check if request is for an image at root. Add/remove file types if necessary.
RewriteCond %{REQUEST_URI}  ^/([^.]+)\.(png|jpg|gif|css) [NC]
RewriteCond %{REQUEST_URI}  !/website_1  [NC]
# Rewrite request to point to "website_1" directory
RewriteRule .*               /website_1/%1.%2          [L,NC]