2016-04-08 85 views
7

我希望能够给所有子域名重定向到一个文件夹:htaccess的重定向所有子域到同一个目录

RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$ 
RewriteRule (.+)$ "http://example.com/subdomains/%1" [L,P] 

例如,如果一些访问sub1.example.com它将保持URL,但显示example.com/subdomains/sub1如果SUB1目录不存在,它会显示example.com/404

这可能吗?

我试过上面的代码,但它给我看:

Forbidden 
You don't have permission to access /index.php on this server. 

的WordPress说:

# BEGIN WordPress 
<IfModule mod_rewrite.c> 
RewriteEngine On 
RewriteBase/
RewriteRule ^index\.php$ - [L] 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule . /index.php [L] 
</IfModule> 

# END WordPress 

,并在我的htaccess文件的顶部,是:

RewriteEngine On 
DirectoryIndex index.php 

RewriteCond %{HTTP_HOST} admin.domain.com$ 
RewriteRule ^(.*)$ /admin/system/$1 [L] 
+0

如果你直接去'http:// example.com/subdomains/sub1 /'怎么办?你是否也有'Forbidden'错误或者你有权访问它?无论如何,尽管事实并非如此,你的代码仍然可以工作。而且我认为它实际上工作。当你有这个'禁止',你看到'sub1.example.com'为url? –

+0

没有错,没有错误 – charlie

+0

代码对我来说也很好。禁止的问题可能由其他.htaccess设置引起,例如在IndexIgnore上。检查你的位置。 –

回答

10

当您使用完整的URL作为目标时,上面的.htaccess会在外部重定向调用。

在你的问题中,你说你想保留主机名,所以我会认为这是要求。

0)使能重写引擎

RewriteEngine On 

1)重写已知的子域,以他们的目录中/子域

# Rewrite known subdomains to /subdomains/{subdomain}/ 
RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$ 
RewriteCond %{REQUEST_URI} !^/subdomains [NC] 
RewriteCond %{REQUEST_URI} !^/404 [NC] 
RewriteRule ^(.+)$ /subdomains/%1/ [L] 
  1. 当我们遇到一个子域的请求,
  2. 和我们没有将其重写到/子域名
  3. 并且我们还没有将其重写到/ 404
  4. 然后重写/子域/ {子域}/

所以,如果请求

http://foo.example.com/hello 

在浏览器的URL将保持不变,但在内部被映射到

/subdomains/foo/ 

2)重写未知子域/ 404

# Rewrite missing unknown subdomains to /404/ 
RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$ 
RewriteCond %{REQUEST_URI} ^/subdomains [NC] 
RewriteCond %{REQUEST_URI} !^/404 [NC] 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-l 
RewriteRule ^(.+)$ /404/ [L] 
  1. 当我们遇到一个子域的请求,
  2. ,我们已将其改写成/子域
  3. ,我们还没有它改写为/ 404
  4. ,它是不存在的文件
  5. 并且没有现有作为目录
  6. 并且它不存在作为一个符号链接
  7. 然后将其重写到/ 404

所以,如果请求

http://bar.example.com/hello 

在浏览器的URL将保持不变,但在内部由1第一RewriteRule被映射到

/subdomains/bar/ 

)。

如果/subdomains/bar/不存在,从2秒RewriteRule)将踢并在内部将其映射到

/404/ 

3)测试环境

我实际上与示例性代码测试的所有的这一点,这里可用:https://github.com/janpapenbrock/stackoverflow-36497197

+0

我也有WordPress的安装 - 我把这两部分代码的上面或下面的WordPress代码? – charlie

+0

你使用WordPress的这些子域名或只是主域名?如果只是主要的,我会尝试把它放在上面。 –

+0

它只是主域名 - wordpress只在主域名上运行。香港专业教育学院试图把它放在上面,它的工作原理,但停止工作的主要领域(WordPress的),如果我把它放在下面,WordPress的作品,但没有子域做 – charlie

3

我假设您遇到许可问题。我猜你的Apache服务器运行为apache用户。使用chmod可以给apache访问此路径。

相关问题