【问题标题】:htaccess redirect all subdomains to the same directoryhtaccess 将所有子域重定向到同一目录
【发布时间】:2023-03-27 07:19:01
【问题描述】:

我希望能够将所有子域重定向到一个文件夹:

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]

【问题讨论】:

  • 直接去http://example.com/subdomains/sub1/怎么办?您是否也有Forbidden 错误或者您可以访问它?不管怎样,你的代码应该可以工作,尽管它写得不好。我认为它确实有效。当您拥有此Forbidden 时,您是否将sub1.example.com 视为网址?
  • 不,工作正常,没有错误
  • 代码对我来说也很好。禁止问题可能是由其他 .htaccess 设置引起的,例如在 IndexIgnore 上。检查您的目的地。

标签: apache .htaccess


【解决方案1】:

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

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

0) 启用重写引擎

RewriteEngine On

1) 将已知子域重写到它们在 /subdomains 中的目录

# 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. 我们还没有将其重写为 /subdomains
  3. 我们还没有将其重写为 /404
  4. 然后将其重写为 /subdomains/{subdomain}/

所以,如果请求是

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. 我们已经将其重写为 /subdomains
  3. 我们还没有将其重写为 /404
  4. 它不作为文件存在
  5. 它不作为目录存在
  6. 它不作为符号链接存在
  7. 然后将其重写为 /404

所以,如果请求是

http://bar.example.com/hello

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

/subdomains/bar/

来自 1) 的第一个 RewriteRule

如果 /subdomains/bar/ 不存在,则 2) 中的第二个 RewriteRule 将启动并在内部将其映射到

/404/

3) 测试环境

我实际上使用示例代码测试了所有这些,可在此处获得:https://github.com/janpapenbrock/stackoverflow-36497197

【讨论】:

  • 我也安装了 Wordpress - 我将这两部分代码放在 wordpress 代码的上方还是下方?
  • 您对这些子域使用wordpress 还是只对主域使用wordpress?如果只是为了主要,我会尝试把它放在上面。
  • 它只是主域 - wordpress 仅在主域上运行。我尝试将它放在上面并且它可以工作,但是会停止主域(wordpress)的工作,如果我把它放在下面,wordpress 可以工作,但没有一个子域可以
  • 您是否使用 www. 调用您的主域?
  • RewriteCond %{HTTP_HOST} !^www\.example\.com$
【解决方案2】:

我会说您遇到了权限问题。我猜您的 Apache 服务器以 apache 用户身份运行。使用chmod 授予apache 访问此路径的权限。

【讨论】:

    猜你喜欢
    • 2016-02-19
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    相关资源
    最近更新 更多