如何使用 .htaccess 而不是 VHost 将文档根目录设置为子目录 [英] How to set document root to be a subdirectory using .htaccess and not VHost
问题描述
在我的本地机器上,以下工作完美:
On my local machine the following works perfect:
<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>
然而,我将我的网站托管给名为 justhost.com 的托管公司,他们不允许我修改 httpd-vhosts.conf 或 httpd.conf强>.现在我的整个站点都经过编码,以便 website_1 下的文件使用简单的斜杠/"引用 website_1 下的其他文件,这意味着 website_1 被视为文档根目录.这在本地机器上完美运行,但是当上传到主机时,它会给我服务器错误,因为无法找到文件,因为它试图在 public_html
Howerver Im hosting my website to hosting company called justhost.com and they do not allow me to modify httpd-vhosts.conf or httpd.conf. Now my entire site is coded so that files under website_1 reference to other files under website_1 using simple slash "/" meaning website_1 is treated as document root. This works perfectly on local machine but when uploaded to host it gives me server errors because cant find the files since its trying to locate those files in public_html
例如:
public_html
- website_1
- script.php
- style.css
在我的 script.php 中:
<a href="/style.css">See My Style</a>
这在本地机器上运行良好,但在主机上它失败了,因为它试图在 public_html 而不是 public_html/website_1
this works good on local machine but on host it fails since it tries to locate style.css under public_html and not public_html/website_1
有没有办法在不使用 VHost 的情况下拥有多个文档根?就像使用 .htaccess 或其他东西一样.请我尽量避免重写代码,因为它大约有 1 万行代码.
Is there a way to have multiple document roots without using VHosts? Like using .htaccess or something else. Please I want to try to avoid rewriting the code as much as possible since its around 10 thousands lines of code.
推荐答案
通过 httpd.conf
启用 mod_rewrite 和 .htaccess 然后把这段代码放到你的 .htaccess
下DOCUMENT_ROOT
目录:
Enable mod_rewrite and .htaccess through httpd.conf
and then put this code in your .htaccess
under DOCUMENT_ROOT
directory:
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
(永久重定向).
Once you verify it is working fine, replace R=302
to R=301
. Avoid using R=301
(Permanent Redirect) while testing your mod_rewrite rules.
这篇关于如何使用 .htaccess 而不是 VHost 将文档根目录设置为子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!