如何用htaccess在子目录中重写或重定向?

时间:2016-10-04 07:57:44

标签: .htaccess

我很难理解htaccess重写/重定向是如何工作的。我已经有超过20篇关于它的文章,但我没有理解如何正确编写规则的逻辑和语法。

我目前有一个带有public_html文件夹的服务器 我们的主站点位于子文件夹/站点下,这是一个wordpress站点 我们在子文件夹/培训下使用其他网站(也是一个wordpress网站)进行电子学习

我需要让我们的网站(domain.com)指向/ public_html / site,同时让domain.com/learning指向public_html / training

我试图了解htaccess中的查询是如何工作的,例如RewriteCond或RewriteRule

这是我目前的代码:

bb

1 个答案:

答案 0 :(得分:1)

以下代码需要添加到主机帐户的public_html文件夹中的.htaccess文件中。

您需要插入以下代码块并进行修改,如(#)注释中所述。

# .htaccess main domain to subdirectory redirect
# Do not change this line.
RewriteEngine on
# Change domain.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?domain.com$
# Change 'site to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/site/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'site' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /site/$1
# Change domain.com to be your main domain again.
# Change 'site' to be the directory you will use for your main domain
# followed by / then the main file for your site, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?domain.com$
RewriteRule ^(/)?$ site/index.html [L] 

为学习域重复相同。

您网站的访问者将无法判断您的主域名是否正在使用子目录,他们仍会将网站地址视为

  

http://www.domain.com/index.html

注意:

  

请注意,这不适用于某些网站软件。您   可能还需要修改$ base_url,$ live_site或其他   配置设置以完成该过程。

既然你提到你的案子是WordPress,那么别忘了看看这个

  

https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory

更新:

RedirectMatch 301 /learning/(.*) /training/$1

# .htaccess main domain to subdirectory redirect
# Do not change this line.
RewriteEngine on
# Change domain.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?domain.com$
# Change 'site to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/site/
# Don't change the following two lines.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'site' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /site/$1
# Change domain.com to be your main domain again.
# Change 'site' to be the directory you will use for your main domain
# followed by / then the main file for your site, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?domain.com$
RewriteRule ^(/)?$ site/index.php [L]