用.htaccess将主域名从网站根目录指向子目录

这个博客原本是要访问 http://www.qiangblog.com/blog/ 来访问的。

我在根目录下放了一个 index.html ,里面的 js 控制自动跳转到 /blog。这样一来,访问http://www.qiangblog.com/ 会自动跳到 http://www.qiangblog.com/blog/ 去。

但是今天突然想把自己的网站整一下,因为这个自动跳转很不利于SEO,而且 qiangblog 这个域名有很强的博客意向。如果总有个 /blog 挂在后面感觉不好看呐。所以我想弄成直接访问 http://www.qiangblog.com/ 就到博客里。并且相应的子目录依旧能用 http://www.qiangblog.com/subdir 访问。

最简单的方法是把 wordpress 装在虚拟主机的根目录下。但是这样目录会变得杂乱,其他项目会跟博客弄到一起,对于整洁强迫症的我来说万万不可。后来看到 wordpress 里有自带一种方法实现这个功能。但是还是要改变目录结构,依旧不能达到我的要求。

今天看到一个 .htaccess 的设置方法。可以实现我想要的效果。编辑根目录下的 .htaccess ,设置好相应参数就完全可以实现我想要的功能了。利于SEO是最爽的事情了~

代码如下:

# .htaccess main domain to subfolder redirect
# Copy and paste the following code into the .htaccess file
# in the public_html folder of your hosting account
# make the changes to the file according to the instructions.

# Do not change this line.

RewriteEngine on

# Change yourdomain.com to be your main domain.

RewriteCond %{HTTP_HOST} ^(www.)?yourmaindomain.com$

# Change ’subfolder’ to be the folder you will use for your main domain.

RewriteCond %{REQUEST_URI} !^/subfolder/

# Don’t change this line.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Change ’subfolder’ to be the folder you will use for your main domain.

RewriteRule ^(.*)$ /subfolder/$1

# Change yourdomain.com to be your main domain again.
# Change ’subfolder’ to be the folder 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.)?yourmaindomain.com$
RewriteRule ^(/)?$ subfolder/index.php [L]